You are not logged in.

#2526 2015-01-17 20:44:44

Rokixz
Member
From: Šiauliai, Lithuania
Registered: 2007-04-21
Posts: 251
Website

Re: Post your handy self made command line utilities

Hello everyone,

Here's my noobish bash script to check disk speed with dd only.

#!/bin/bash

# Check for 250MB>= free space 
  diskspace=$(df -m . | tail -n 1 | awk {'print $4'})
if [ "$diskspace" -lt 250 ];
  then
    echo -n "Not enough free space on device "; echo -n $diskspace; echo MB/250MB, please make some space and run script again.
    exit 1
fi
  curfile=`basename $0`
 
  echo -n "1) Test disk read speed. 2) Test disk write speed. 0) Exit script. Enter preferred option: "
  
  read  option

case $option in
  0)
    option="0";
    ;;
  1)
# Creating files for read
    for i in 10 50 100 200; do
    echo -n "Creating $i"
    echo "MB file for data read test"
    dd if=/dev/urandom of=testfile bs=1M count=$i > /dev/null 2>&1
    sync
    dd if=testfile of=/dev/null bs=1M count=$i 
    rm -rf testfile; done
## Reading pseudo data from zero device.
#    echo "Testing read speed, please wait..."
#    for i in 10 50 100 200; do
#    echo -n Reading $i; echo MB of data: 
#    dd if=/dev/zero of=/dev/null bs=1M count=$i; done
    ;;
  2)
# Writing pseudo data (urandom) to temporarily localfile.
      echo "Testing write speed, please wait..."
if [ -f testfile ];
  then
    rm -rf testfile;
    for i in 10 50 100 200; do
    echo -n Writing $i; echo MB of data: 
    dd if=/dev/urandom of=testfile bs=1M count=$i conv=fdatasync &&
    rm -rf testfile &&
    sync;  done
else
    for i in 10 50 100 200; do
    echo -n Writing $i; echo MB of data: 
    dd if=/dev/urandom of=testfile bs=1M count=$i conv=fdatasync &&
    rm -rf testfile; done
fi
    ;;
  *)
    echo "Uknown option, please select one of the following below: "
    ./$curfile
    exit 0 
    ;;
esac

# Repeat script or exit if stated.
if [ $option == 0 ];
  then
    echo Goodbye!
    exit 0
else
   echo -n "Test it again? (y/n): "
   read repeat
if [[ $repeat == "y" ]] || [[ $repeat == "Y" ]];
  then
    ./$curfile
else
  echo Goodbye!
  exit 0
fi
fi

# End of file

Sometimes I need to check disk speed of the kvm machines so it helps sometimes to save some time. The purpose of writing this script was to learn something new, hope to write some other scripts while on free time.


http://ispconfig.lt - ISPConfig 3 based hosting. Coming Soon!

Offline

#2527 2015-01-17 21:11:02

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Any reason that you alternate between `[` and `[[`? See http://mywiki.wooledge.org/BashFAQ/031
Also, you don't need the `tail` process:

df -m . | awk 'NR==2 {print $4}'

Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2528 2015-01-22 14:51:01

Alad
Wiki Admin/IRC Op
From: Bagelstan
Registered: 2014-05-04
Posts: 2,407
Website

Re: Post your handy self made command line utilities

Typically you want to associate lots of mime types to a particular application (editor, image viewer, etc.). You can use an external tool for this, the app itself if it supports such, or a 5-liner bash script:

#!/bin/bash
read -p "Enter a mime glob pattern. " PATTERN
TYPES=($(grep "$PATTERN" /etc/mime.types | awk '{ print $1 }'))
read -p "Enter a desktop file. " DESKTOP
xdg-mime default "$DESKTOP" "${TYPES[@]}" && echo "New default set."

Alternatively, use grep -P for perl regex.

Last edited by Alad (2015-01-22 14:56:08)


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby

Offline

#2529 2015-01-25 10:31:24

mikesd
Member
From: Australia
Registered: 2008-02-01
Posts: 788
Website

Re: Post your handy self made command line utilities

Prior to setting up LUKS, or any other full disk encryption, it's a good idea to fill the disk with random data. Our wiki, and most other docs, suggest something like:

# openssl enc -aes-256-ctr -pass pass:"$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64)" -nosalt

Unfortunately this leave the encryption key visible, e.g. via ps, for the duration of the wipe. I wrote a thin wrapper that passes the key via a file descriptor which is a better alternative than either passing via command line or env variable. Script is here.

Offline

#2530 2015-01-26 15:37:47

thiagowfx
Member
Registered: 2013-07-09
Posts: 586

Re: Post your handy self made command line utilities

Those originated from here.

# pacman qkkdiffs
pacman-qkkdiff-file() {
    if [[ "$1" == "" ]]; then
        cat <<EOF
Purpose: get the changes between this file now and in the upstream package
Usage: qkkdiff-file <file>
Example: qkkdiff-file /etc/pacman.conf"
EOF
    elif [[ -f "$1" ]]; then
        pkg="$(pacman -Qo $1 | awk '//{printf "%s-%s", $(NF-1), $NF;}')"
        bsdtar -xOf /var/cache/pacman/pkg/${pkg}-$(uname -m).pkg.tar.xz "${1/\//}" | diff - "$1"
        return 0
    else
        echo "The provided file \e[0;31m${1}\e[0m does not exist."
        return 1
    fi
}

pacman-qkkdiff-pkg() {
    if [[ "$1" == "" ]]; then
        echo <<EOF
Purpose: get the changes between the upstream package and the files on the filesystem
Usage: qkkdiff <package>
Example: qkkdiff pacman
EOF
    elif ! pacman -Q "$1"; then
        return 1
    else
        ver=$(pacman -Q "$1" | cut -f2 -d' ')
        pacman -Qkkq "$1" | while read package file; do echo $file; bsdtar -xOf /var/cache/pacman/pkg/${package}-${ver}-$(uname -m).pkg.tar.xz ${file/\//} | diff - $file  ; done
        return 0
    fi
}

Offline

#2531 2015-01-27 23:43:10

snakeroot
Member
Registered: 2012-10-06
Posts: 164

Re: Post your handy self made command line utilities

Compose key utility

A configured compose key is a wonderful thing. However, remembering the key combinations can be difficult (even the ones you configured yourself in $HOME/.XCompose). And searching the Compose file is not a lot of fun, since it is large (500K text file) and long (6,019 lines).

This utility creates a stripped down version of the combined Compose and XCompose file and searches the comment portion of each line for selected keywords and letters. It is case sensitive as to single letters and allows for substitution of more common words (umlaut) for Compose-specific equivalents (diaeresis).

The utility is written for the en_US.UTF8 locale and generic en_us/pc104 keyboard with no keypad, but should be easy to customize to different locales, keyboards and users. THE UTILITY REQUIRES BASH 4+.

#!/bin/bash

# Print help if run with no parameters
# 
if [[ "$#" -lt 1 ]]; then
echo ""
echo "Shows compose key combinations found using search terms on"
echo "the command line. Result must contain ALL search terms. Both"
eco "the standard Compose file and user specified XCompose file"
echo "are included in the search."
echo ""
echo "Single letters are case sensitive."
echo ""
echo "Numbers are not accepted."
echo ""
exit 3
fi

# Fail if any paramaters are non-alpha
# 
echo "$@" | /bin/grep -qi [^[:alpha:][:blank:]] && echo "ERROR: All parameters must be alpha" && exit 4

# Fail if bash lt version 4
#
[[ $(/bin/bash --version | /bin/sed -nr -e '1s/(.*version )(.)(\..*)/\2/p') -lt 4 ]] && echo "ERROR: Bash 4+ required" && exit 5

# Locations for Compose and XCompose files and stripped combination of the two
#
CharFile="/usr/share/X11/locale/en_US.UTF-8/Compose"
XCompose="$HOME/.XCompose"
LocCompose="$HOME/.config/LocCompose"

# Strips out lines with keys which are absent from stripped file
#
disallowed( ) {
/bin/sed -i -r -e '/ <U[0-9a-fA-F]{4}>/d' \
-e '/ <U[0-9a-fA-F]{5}>/d' \
-e '/ <KP_/d' \
-e '/ <Cyrillic_/d' \
-e '/ <dead_/d' \
-e '/ <Greek_/d' \
-e '/ <Arabic_/d' \
-e '/ <kana_/d' \
-e '/ <[aeiouAEIOU]*macron>/d' \
-e '/ <[aeiouAEIOU]*diaeresis>/d' \
-e '/ <[aeiouAEIOU]*horn>/d' \
-e '/ <[aeiouAEIOU]*circumflex>/d' \
-e '/ <[cC]*edilla>/d' \
-e '/ <[aeiouAEIOU]*tilde>/d' "${1}"
}

# Only allows lines which begin with <Multi_key into stripped file
#
allowed( ){
/bin/sed -n -i -e '/^<Multi_key/p' "${1}"
}

# Creates or recreates new stripped file (if Compose or XCompose have been updated) 
# 
if [[ -r "${XCompose}" ]]; then
	if [[ "${LocCompose}" -ot "${CharFile}" ]] || [[ "${LocCompose}" -ot "${XCompose}" ]]; then
		/bin/cat "${CharFile}" "${XCompose}" > "${LocCompose}"
		allowed "${LocCompose}"
		disallowed "${LocCompose}"
	fi 
else
	if [[ "${LocCompose}" -ot "${CharFile}" ]]; then
		/bin/cp "${CharFile}" "${LocCompose}"
		allowed "${LocCompose}"
		disallowed "${LocCompose}"
	fi
fi

# Parses single letters based on case and substitutes synonyms for Compose file vocabulary
#
parser( ){
local parsed=${1}
if [[ ${#parsed} -eq 1 ]]; then
	case $parsed in
		[[:lower:]]) parsed="SMALL LETTER $parsed "
		;;
		[[:upper:]]) parsed="CAPITAL LETTER $parsed "
	esac
fi

parsed=${parsed^^}
case "${parsed}" in
	UMLAUT) parsed="DIAERESIS"
	;;
	PARAGRAPH) parsed="PILCROW"
	;;
	HOOK) parsed="(CEDILLA|OGONEK|HOOK)"
	;;
	HAT) parsed="CIRCUMFLEX"
	;;
	SMILE) parsed="CARON"
	;;
	SLASH) parsed="STROKE"
	;;
	BAR|LONG) parsed="MACRON"
	;;
	GBP) parsed="POUND"
	;;
	JPY) parsed="YEN"
	;;
	EUR) parsed="EURO"
esac
echo "${parsed}"
}

# Creates temp file, copies stripped file to it and uses sed to find lines based on comments
#
tmp_fil=$(/bin/mktemp)
/bin/cat "${LocCompose}" >> "${tmp_fil}"
for i in "$@"; do
	PAT=$(parser "${i}")
	/bin/sed -i -n -r -e "s/(.*# )(.*${PAT}.*)/\1\2/pg" "${tmp_fil}"
done
/bin/cat "${tmp_fil}"
/bin/rm "${tmp_fil}"

Offline

#2532 2015-01-31 13:36:36

Awebb
Member
Registered: 2010-05-06
Posts: 6,272

Re: Post your handy self made command line utilities

Scroll down for the final version. Thinking happened while posting :-)

From this discussion. The task was to have an easy way to know what non-free packages would be pulled aboard. It was proposed, that pacman should warn the user about non-free packages, however pacman has a long tradition of not bothering the user with non-technical questions. Since many people use their own wrappers and aliases for pacman, this could come in handy.

for i in `pactree -sld1 MY_FANCY_PACKAGE`; do echo $i `pacman -Si $i | grep Licenses`; done

It displays a package and its first level of dependencies and outputs the license according to pacman.

Here, the quick'n'dirty bashrc function version:

paclic() {
	if [[ -z $2 ]];
	then
		depth="1"
	else
		depth=$2
	fi
	for i in `pactree -sld $depth $1`; do
		echo $i `pacman -Si $i | grep Licens`
	done
}

Usage:
paclic [packagename] [depth]

Like:
paclic bash 2

Depth is optional, it will default to 1 of omitted.

We could expand this by whitelisting the free licenses, but I am not overly interested in the discussion beyond the opensource question.

Furthermore, since we talk about licenses here, if anybody is interested in turning this into more than an educational draft, give me some credit (link to this thread, name mention, something like that) and please pick an opensource license.

EDIT: And, please, for any discussion regarding licenses, use the thread linked above or any of the other license discussions.

EDIT: Thanks, Earnestly. Here, an expac version:

paclic() {
    if [[ -z $2 ]];
        then
            depth="1"
        else
            depth=$2
        fi
        pactree -sld $depth $1 | xargs expac -S '%n: %L' 
} 

EDIT: Wooohoooo! The expac-less version is really really really slow compared to that expac pipe. Instead of calling pacman a million times, we simply look at the database twice.

EDIT: I have spent way more time with this thing, than I intended.

Here, it checks for expac and falls back to crawling through pacman calls if required:

paclic() {
	if [[ -z $2 ]];
	then
		depth="1"
	else
		depth=$2
	fi
	if [[ -e /usr/bin/expac ]];
	then		
		pactree -sld $depth $1 | xargs expac -S '%n: %L'
	else
		for i in `pactree -sld $depth $1`; do
			echo $i `pacman -Si $i | grep Licens`
		done
	fi
}

Last edited by Awebb (2015-01-31 15:25:00)

Offline

#2533 2015-01-31 14:09:45

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

Have you hard of expac?

expac '%n: %L'

Last edited by Earnestly (2015-01-31 14:10:07)

Offline

#2534 2015-01-31 15:06:32

Awebb
Member
Registered: 2010-05-06
Posts: 6,272

Re: Post your handy self made command line utilities

Earnestly wrote:

Have you hard of expac?

expac '%n: %L'

Yes. marvelous tool, this expac! It could iterate through "expac -S -l "\n" %E", collect all packages, sort|uniq and then expac '%n: %L'. We could also combine pactree and expac to reduce the impact, because pactree is in the pacman package, which is why I did not use expac, because it is an additional package. Edited my post above.

Last edited by Awebb (2015-01-31 15:15:21)

Offline

#2535 2015-02-05 16:57:57

Alad
Wiki Admin/IRC Op
From: Bagelstan
Registered: 2014-05-04
Posts: 2,407
Website

Re: Post your handy self made command line utilities

I got bored with copy/pasting commands from the mimeo --help, so I wrote this:

#!/usr/bin/env bash

browse_bin=(firefox chromium conkeror vimperator midori rekonq opera)
jpg_bin=(nomacs gimp gpicview gthumb gwenview feh sxiv)
txt_bin=(emacsclient gvim gedit medit leafpad)
pdf_bin=(qpdfview evince okular mupdf)
dir_bin=(mc pcmanfm nautilus krusader thunar)

def_which() {
    for i in "${def_bin[@]}"; do
	which "$i" &>/dev/null &&
	    def_avail+=("$i")
    done
}

def_select() {
    def_which
    if (( ${#def_avail[@]} > 0 )); then
	echo "Select an executable:"
	select ex in "${def_avail[@]}"; do
	    break
	done
    else
	echo "No defaults available."
	return 1
    fi
}

if_desk() {
    desk_avail=($(mimeo --app2desk "$1" | awk '/desktop/ { print $1 }'))
    if (( ${#desk_avail[@]} > 0 )); then
	echo "Select a desktop file:"
	select def_desk in "${desk_avail[@]}"; do
	    break
	done
    else
	[[ $1 ]] && {
	    echo "Warning: using executable as desktop name..."
	    def_desk="$1".desktop
	}
    fi
}

case "$1" in
    jpg)
	def_bin=("${jpg_bin[@]}")
	def_select
	if_desk "$ex" &&
	    mimeo --prefer 'regex:^image/(png|jpe?g|gif|tif?f)$' "$def_desk"
	;;
    txt)
	def_bin=("${txt_bin[@]}")
	def_select
	if_desk "$ex" &&
	    mimeo --prefer 'regex:^text/(x-.*|english|plain)' "$def_desk"
	;;
    dir)
	def_bin=("${dir_bin[@]}")
	def_select
	if_desk "$ex" &&
	    mimeo --prefer inode/directory "$def_desk"
	;;
    pdf)
	def_bin=("${pdf_bin[@]}")
	def_select
	if_desk "$ex" &&
	    mimeo --prefer 'regex:^.*/(x-)?(pdf|djvu)$' "$def_desk"
	;;
    www)
	def_bin=("${browse_bin[@]}")
	def_select
	if_desk "$ex" && {
	    mimeo --prefer 'regex:^(message|x-scheme-handler)/(rfc822|(s-)?https?|about|ftp)' "$def_desk"
	    mimeo --prefer 'regex:^(text|application)/x?(ht|m)ml(\+xml)?' "$def_desk"
	} ;;
    *)
	echo "Options: jpg|txt|dir|pdf|www"
	;;
esac

It sucks how Firefox & friends use mimeapps directly instead of xdg-open, else I needn't bother with all this *desktop stuff... still, mimeo works pretty well.

Last edited by Alad (2015-02-05 16:59:50)


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby

Offline

#2536 2015-02-05 21:19:55

Ledti
Member
Registered: 2010-07-31
Posts: 122
Website

Re: Post your handy self made command line utilities

I couldn't find a Tarsnap script that I liked, so I wrote one the other day that I'm calling tarcinch.

* Daily backups (optional).
* Weekly backups (optional).
* Monthly backups (optional).
* Configurable prune functionality for each type.
* Will at most create 1 backup and potentially prune 1 backup per day.
* Standalone so you can duplicate and run the script multiple times with different options.

I run it daily with a systemd --user service/timer.

* I haven't actively tested everything yet, so some functionality may be broken.

Last edited by Ledti (2015-02-05 21:56:51)

Offline

#2537 2015-02-06 03:31:47

HalosGhost
Forum Moderator
From: Twin Cities, MN
Registered: 2012-06-22
Posts: 2,089
Website

Re: Post your handy self made command line utilities

I'm working on converting this to an actual C application to remove the hard dependencies on awk and steamcmd. However, if you play steam games and ever want to run just the client without the full UI, you can run the following:

$ steam -applaunch <appID>

The problem is, the appIDs are a pita to find (there's a website that tracks all of them but who has time for that?). Luckily, steamcmd actually provides a way to find this information for installed games. Unfortunately, steamcmd sucks rather badly, and the command doesn't just recovery appIDs, it recovers everything (which makes it a pain to read). Thus, I have this small script:

#!/usr/bin/bash

steamcmd '+apps_installed +quit' |\
    awk '/AppID/ {
             id = $2;
             name = substr($0, index($0, " : ") + 3);
             sub(" : .*", "", name);
             print id ": " name;
         }'

Yes, I'm calling awk from inside bash instead of just using awk, but really this whole thing is an ugly hack anyway to tide me over till I get the C util written. The end result of running this is that it outputs the names of all your installed steam games and their associated appIDs.

As with all my simple utils, you can find it on my GitHub (link below in my signature).

All the best,

-HG

Offline

#2538 2015-02-06 13:37:34

fsckd
Forum Fellow
Registered: 2009-06-15
Posts: 4,173

Re: Post your handy self made command line utilities

I have some of my scripts to operate not just on the cwd but on the subdirectories as well. Rather than creating recursion options in each script, I made this wrapper which I call recurse.

How to invoke:

  1. recurse directories... -- command parameters...

  2. recurse -- command parameters...

  3. recurse command parameters...

The '--' separates list of directories from the command to invoke. In the first form, run the command in the directories listed and in their subdirectories. In the second and third forms, run the command in the current working directory and its subdirectories. The second form is for situations where one of the command's parameters is a '--'.

These three examples should have the same output:

$ recurse /usr/bin -- pwd
$ cd /usr/bin ; recurse -- pwd
$ cd /usr/bin ; recurse pwd

The script itself:

#!/bin/bash

# predicate to check if any arg is '--'
hassep() {
  local has=1 a
  for a in "$@"
  do [[ "$a" == '--' ]] && has=0 && break
  done
  return $has
}

declare -a dirs # array of dirs to search

if hassep "$@"
then # directories are listed in args
     while (( $# ))
     do if [[ "$1" == '--' ]]
        then shift ; break
        else dirs+=( "$1" ) ; shift
        fi
     done
fi

# dirs cannot be empty
[[ "${#dirs[@]}" == 0 ]] && dirs=( . )

if ! (( $# ))
then echo No command given.
     exit 1
fi

find "${dirs[@]}" -type d -exec bash -c 'cd "$0" ; "$@"' {} "$@" \; 

aur S & M :: forum rules :: Community Ethos
Resources for Women, POC, LGBT*, and allies

Offline

#2539 2015-02-06 17:11:18

helix
Member
Registered: 2013-02-17
Posts: 180

Re: Post your handy self made command line utilities

This is a script I'm using to generate the virtual packages list that I use inside my debtap script:

#!/usr/bin/bash

expac -Ss %P > tempfile1

cat tempfile1 | while read line; do
for word in $line; do
    echo $word >> tempfile2
done; done

for i in `sort -u tempfile2`; do
    pacman -Ssq `echo $i | sed s'/=\|>\|</ /' | gawk '{print $1}'` > result
    grep -q "^$(echo $i | sed s'/=\|>\|</ /' | gawk '{print $1}')$" result || echo $i | sed s'/=\|>\|</ /' | gawk '{print $1}' >> tempfile3
done

sort -u tempfile3 > virtual-packages-list

Offline

#2540 2015-02-06 17:47:12

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

For the first two loops consider:

while read -d' ' -r word; do echo "$word"; done < <(expac -Ss %P) | sort -u > tmp

Offline

#2541 2015-02-10 17:36:14

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 813
Website

Re: Post your handy self made command line utilities

A little personality via dmesg & speech-dispatcher:

#The basic premise (verbose and illegible)
#dmesg -w | spd-say -e

#Clear the ring buffer; don't read out all the messages before we got here.
#Only seems to be needed for spd-say -P important (which is actually default, not "text")
#dmesg -C

#Log output detail and style
DMESGOPTS="-HPkutw --level=emerg,alert,crit,err,info"

#Voice settings
SPEECHOPTS="-R +10 -p +70 -i -25 -t female1 -P notification"

#Sed filters make dmesg output conversational
#Nearly everything in [] is illegible
FILTERS="s|\[[a-zA-Z0-9()-+  ]*\]||g"
#Simplify segfault notification
FILTERS+=";s|segfault.*$|crashed: segfault|g"
#Simplify new (usb?) device connected notification
FILTERS+=";s|new .* using|connected:|g"
#Simiplify device declaration statement
FILTERS+=";s| as .*$||g;s| on .*$||g"
#Simplify device disconnected notification
FILTERS+=";s|[a-zA-Z0-9]* disconnect.*$|disconnected|g"
#Spell out module names (need a whole database of these)
FILTERS+=";s|ehci|E-H-C-I|g;s|hiddev|H-I-D-dev|g;s|hidraw|H-I-D-raw|g"

#Output dmesg to speech-dispatcher
dmesg $DMESGOPTS | sed -u "$FILTERS" | spd-say -e $SPEECHOPTS > /dev/null 2>&1

EDIT: Over the years several tts implementations have collapsed on me. speech-dispatcher can no longer be made to work at all; festival doesn't work with the hts voices without patches; the hts voices don't work with patched festival without patches; espeak only works half of the time; flite doesn't work with the hts voices at all... In addition to that, systemd's journalctl has irrevocably taken over the role of dmesg.

Rewritten for journalctl and flite_hts_engine:

#!/bin/bash

#For journalctl
JCTLOPTS="--utc -fk -o cat -p 7 --since $(date +%H:%M:%S)"

#Sed filters to make output "conversational"

#Nearly everything in [] is illegible
FILTERS="s|\[.*\]||g"

#Simplify device connected notification
FILTERS+=";s|new [a-zA-Z0-9]* using|connected:|g"
#Simplify device disconnected notification
FILTERS+=";s|[a-zA-Z0-9]* disconnect.*$|disconnected|g"
#Simiplify device declaration statement
FILTERS+=";s| as .*$||g;s| on .*$||g"

#Spell out module names
FILTERS+=";s|ehci|E-H-C-I|g;s|hiddev|H-I-D-dev|g;s|hidraw|H-I-D-raw|g;s|pci|P-C-I|g;s|efi|E-F-I|g;s|acpi|A-C-P-I|g"

#Simplify segfault notification
FILTERS+=";s|segfault.*$|crashed: segfault|g"
#Simplify trap notification
FILTERS+=";s| trap .*$||g;s|ip:[a-z0-9]* sp:[a-z0-9]* error:[a-z0-9]* ||g"

#Output to sdtout (for testing)
textin="/tmp/.dmesg-in" && [[ ! -p "${textin}" ]] && mkfifo -m 600 "${textin}"
wavout="/tmp/.dmesg-out" && [[ ! -p "${wavout}" ]] && mkfifo -m 600 "${wavout}"
htsvoice="/usr/share/hts/voices/english/cmu_us_arctic_slt.htsvoice" && \
  [[ ! -f "${htsvoice}" ]] && echo "HTS voice not available" && exit 1

journalctl $JCTLOPTS | sed -u "$FILTERS" | while IFS= read -r line; do
  echo "${line}" > "${textin}" &
  flite_hts_engine -m "${htsvoice}" \
                   -s 48000 -r 1.3 -fm 0 \
                   "${textin}" -o "${wavout}" &
  paplay -d Center-Mono "${wavout}"
done

Last edited by quequotion (2019-10-06 08:44:30)

Offline

#2542 2015-02-14 02:20:05

Schlunze
Member
Registered: 2013-10-03
Posts: 53

Re: Post your handy self made command line utilities

Hello,

i want to share my first hooks for switching input of two monitors, using xrandr and Signal detection.

After playing around with xrandr i wanted to make a systemd file for it, trial and error -- olways can´t detect display. quick n dirty > xfce autostart
Quite a better idea is using signal detection of monitors to switch inputs and start synergys.

To use self made hooks just create the hooks directory and make the qemu script executable.

mkdir /etc/libvirtd/hooks 
touch /etc/libvirtd/hooks/qemu 
chmod +x /etc/libvirtd/hooks/qemu

write your script.

#!/bin/bash
# use xrandr to switch monitor input on host during start and after stop  VM

Guest_name=vm-client
export DISPLAY=:0

if [ "${1}" = "${Guest_name}" ]; then
        if [ "${2}" = "stopped" ]; then
                        su yourusername -c "/usr/bin/xrandr --output HDMI3 --auto --primary --output HDMI1 --auto --right-of HDMI3"
                        systemctl stop synergys@yourserver
        fi
                if [ "${2}" = "start" ]; then
                        su yourusername -c "/usr/bin/xrandr --output HDMI3 --off --output HDMI1 --auto --primary"
                        systemctl start synergys@yourserver
        fi
fi

restart libvirtd, and worked for me.

Thanks for the useful snippets @
https://wiki.archlinux.org/index.php/xrandr
http://unix.stackexchange.com/questions … op-as-root
https://www.libvirt.org/hooks.html
http://wiki.libvirt.org/page/Networking

Last edited by Schlunze (2015-02-14 10:25:32)

Offline

#2543 2015-02-14 02:23:52

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Merging with the Command Line Utilities thread...


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2544 2015-02-14 10:39:52

Schlunze
Member
Registered: 2013-10-03
Posts: 53

Re: Post your handy self made command line utilities

jasonwryan wrote:

Merging with the Command Line Utilities thread...

thank you for merging, but i wanted to see how other users use hooks in libvirtd, or solve the same problem with betta solution.

Offline

#2545 2015-02-14 11:26:17

Awebb
Member
Registered: 2010-05-06
Posts: 6,272

Re: Post your handy self made command line utilities

quequotion wrote:

A little personality via dmesg & speech-dispatcher:..

Now I have to write something to provoke dmesg activity to test this, because mine is quite calm.

Offline

#2546 2015-02-14 17:06:47

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Schlunze wrote:
jasonwryan wrote:

Merging with the Command Line Utilities thread...

thank you for merging, but i wanted to see how other users use hooks in libvirtd, or solve the same problem with betta solution.

Then you should have included a question(s) in your post... tongue


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2547 2015-02-17 11:50:36

x33a
Forum Fellow
Registered: 2009-08-15
Posts: 4,587

Re: Post your handy self made command line utilities

Awebb wrote:
quequotion wrote:

A little personality via dmesg & speech-dispatcher:..

Now I have to write something to provoke dmesg activity to test this, because mine is quite calm.

Put your machine in a reboot loop for dmesg activity tongue

Offline

#2548 2015-02-17 17:32:20

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 813
Website

Re: Post your handy self made command line utilities

Awebb wrote:

Now I have to write something to provoke dmesg activity to test this, because mine is quite calm.

Pulling out or inserting a usb device usually does the trick! Dmesg is surprisingly not that noisy.

Offline

#2549 2015-02-23 18:02:01

Alad
Wiki Admin/IRC Op
From: Bagelstan
Registered: 2014-05-04
Posts: 2,407
Website

Re: Post your handy self made command line utilities

So I wanted something to quickly turn off my display on battery power, but not on AC, as well as notify me on low battery. There's lots of ways to do this but I wanted something with no dependencies. Only uses DPMS so far. Here goes:

#!/bin/bash

# Allow one instance per X server
# http://jdimpson.livejournal.com/5685.html
lockfile="/tmp/pbat-${DISPLAY#:}.lock"
exec 200>$lockfile
flock -n 200 || exit 1
pid=$$
echo $pid 1>&200

# Be more verbose
case "$1" in
    debug)
	set -x
	;;
    *)	
esac

# Battery path
# 1 Primary, 2 Secondary, 3 Critical threshold (%)
pset1=BAT0
pset2=BAT1
pset3=5

# DPMS (minutes)
# BAT: 1 Standby, 2 Suspend, 3 Off
# AC:  4 Standby, 5 Suspend, 6 Off
xset1=5
xset2=10
xset3=10
xset4=20
xset5=25
xset6=25

# Only evaluate keys which match "p-/xset<0-99>=<0-999>"
# http://wiki.bash-hackers.org/howto/conffile
load() {
    conf="$HOME/.config/pbat.conf"
    unset n
    [[ -r $conf ]] && {
	keys=($(grep -iP '^(p|x)set\d{1,2}=\d{1,3}$' "$conf"))
	eval "${keys[@]}"
    }
}

# Run a command once
run() {
    local i="$1"
    [[ $n != $i ]] && {
	shift; "$@"
	n="$i"
    }
}

# Run `killall -HUP pbat` to reload the configuration
load; trap load HUP

# Clean up on exit
trap "rm $lockfile" EXIT

# Monitor battery status (first battery)
sys="/sys/class/power_supply"
while sleep 5; do
    status=$(cat $sys/$pset1/status)
    capacity=$(cat $sys/$pset1/capacity)
    case "$status" in
	Discharging)
	    if (( capacity < pset3 )); then
		msg="Battery level critical."
		run 1 notify-send -u critical "$msg"
	    else
		run 2 xset dpms $((xset1*60)) $((xset2*60)) $((xset3*60))
	    fi
	    ;;
	*)
	    run 3 xset dpms $((xset4*60)) $((xset5*60)) $((xset6*60))
	    ;;
    esac
done

Change settings:

alias pset='$EDITOR $HOME/.config/pbat.conf && killall -15 pbat'

I only wanted to run the commands once so I could still use xset manually. There's probably a better way to do this .... feel free to advise.

edit: added flock and fixed load().

Last edited by Alad (2015-02-24 03:54:33)


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby

Offline

#2550 2015-02-24 14:07:17

mkoskar
Member
Registered: 2014-07-16
Posts: 64
Website

Re: Post your handy self made command line utilities

I wanted to have something to display current tcp/udp sockets state. I was using "netstat" and then "ss" lately. But I didn't like output (namely "ss | $PAGER" output would be broken). So I went and wrote simple wrapper around these tools which:

1) prints summary ("ss - s")
2) netstat output processing: 0.0.0.0 -> *, 127.0.0.1 -> local, LISTEN -> .LISTEN, ESTABLISHED -> :ESTABLISHED
3) sort by protocol (1st column), state (2nd column; .LISTEN will be on top, followed by :ESTABLISHED), source IP (3rd column; this is simple string sorting)

I'm sure it can be done in nicer way, but this is quiet simple and works well for me. I thought it might for somebody else too wink.

$ cat ~/bin/sstat 
#!/bin/bash

set -e

ss -s

netstat -aptueW --numeric-host --numeric-ports 2>/dev/null |
awk '
NR > 2 {
    format = "%-8s %-15s %-25s %-25s %-10s %-22s\n"

    gsub("0\\.0\\.0\\.0", "*")
    gsub("127\\.0\\.0\\.1", "local")

    if ($1 ~ "^udp") {
        printf(format, $1, "-", $4, $5, $6, $8)
    }
    else if ($1 ~ "^tcp" ) {
        if ($6 == "LISTEN") $6 = "." $6
        else if ($6 == "ESTABLISHED") $6 = ":" $6

        printf(format, $1, $6, $4, $5, $7, $9)
    }
}
' | sort -b -k1,1r -k2,2 -k3,3

Sample output looks like this:

$ sudo sstat
Total: 365 (kernel 596)
TCP:   12 (estab 7, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*	  596       -         -        
RAW	  0         0         0        
UDP	  2         2         0        
TCP	  12        12        0        
INET	  14        14        0        
FRAG	  0         0         0        

udp      -               *:68                      *:*                       root       1031/dhcpcd           
udp      -               local:53                  *:*                       root       13587/dnsmasq         
tcp      .LISTEN         local:53                  *:*                       root       13587/dnsmasq         
tcp      .LISTEN         local:631                 *:*                       root       581/cupsd             
tcp      .LISTEN         local:6667                *:*                       root       1/init                
tcp      .LISTEN         local:8118                *:*                       privoxy    606/privoxy           
tcp      .LISTEN         local:9050                *:*                       tor        601/tor               
tcp      :ESTABLISHED    192.168.100.102:34025     199.16.156.48:443         bitlbee    29590/bitlbee         
tcp      :ESTABLISHED    192.168.100.102:51626     74.125.71.125:5222        bitlbee    29590/bitlbee         
tcp      :ESTABLISHED    192.168.100.102:58542     38.229.70.54:443          tor        601/tor               
tcp      :ESTABLISHED    local:48138               local:9050                miro       29514/weechat         
tcp      :ESTABLISHED    local:53264               local:6667                miro       29514/weechat         
tcp      :ESTABLISHED    local:6667                local:53264               root       1/init                
tcp      :ESTABLISHED    local:9050                local:48138               tor        601/tor               

Last edited by mkoskar (2015-02-24 14:17:16)

Offline

Board footer

Powered by FluxBB