Redirect only stderr
(echo out1;echo out2;ls nonex) 3>&1 1>&2- 2>&3- | wc
Counting Loop
a=1;while test $a -lt 256 ; do echo $a; a=`expr $a + 1`;done
Traps
trap "finish $sig" 0 1 2 3 6 14 15 # $sig contains the actual signal number trap "" 15 # ignore signal trap - 15 # default signal
0 is a pseudo signal, that gets emmited when a shell script ends the normal way.
Check if a command is running and restart if not
if ! ps -p `cat /var/run/command.pid `; then
date >> some.logfile
restart
sleep 10
fi
Kill a command after a specified runtime
command & pid=$! sleep 60 kill $pid
Generate short random string
head -c8 /dev/urandom|od -An -t x8|cut -c2-
Convert epocvalue into date
BSD date: date -r 1138790759
GNU date: date -d @1138790759 or date -d '1970-01-01 1138790759 sec'
Sleep less than 1 second
(e.g. for 0.1 seconds)
Linux: usleep 100000
Other: perl -e 'select(undef,undef,undef,.1)'
Using {} in find
The command find . -name file1 -exec 'mv {} `dirname {}`/file2' \; does not work. The backticks are evaluated before {} is replaced by the file command.
Wrap the command in a shell instead: find . -name file1 -exec sh -c 'mv {} `dirname {}`/file2' \;
Iterating over more than one file
Say there is file a with lines
a b c
and file b with lines
x y z
The Skript iter.sh
while read a; do
read -u 3 b
echo "a=$a b=$b"
doneinvoked as bash iter.sh <a 3<b results in
a=a b=x a=b b=y a=c b=z
It only works this way with Bash!
more elegant
paste a b|while read a b; do echo "a=$a b=$b";done
