20100827

http://www.gfxcoder.us/wiki/programming/bash


Handy BASH reference (link)

robust script writing (link)

lockfile
lockfile a.lock
#do stuff hererm -f a.lock

date (link)

Spicing up your shell script (link)

parameters (link)

Tutorials

misc (linklink)
functions (link)

timing commands
/usr/bin/time -o outfile -v command # prints verbose stats into outfile from running command

BASH internal variables (link)

for loops (link)
for i in 1 2 3 4 5
do
  echo "Welcome $i times"
done

for i in {1..5}
do
  echo "Welcome $i times"
done

for i in {0..10..2} # skip by 2s, only BASH 4.0+
do
  echo "Welcome $i times"
done

for (( c=1; c<=5; c++ ))
do
  echo "Welcome $c times"
done

for i in 1 2 3 4 5
do
  echo "Welcome $i times"
  if ( condition )
  then
    break
  fi
done
# continue - jumps to beginning of loop with next iteration

for file in /etc/*
do
  if [ "${file}" == "/etc/resolv.conf" ]
  then
    echo "file ${file} found!"
  fi
done

files="$@"
for f in $files
do
  if [ -f ${f} ]
  then
    echo "{f} is a file"
  else
    echo "${f} is not a file"
  fi
done

pausing with read (link)
$ read -p "Press enter to quit..."                   # reads one line
$ read -n 1 -p "Press any key to start backup..."    # reads only one char
$ read -n 1 -s -t 5                                  # reads one char, no echo, 5sec timeout
$ read -n 1 -s key                                   # reads one char, no echo, stores in ${key}

terminate commands after timeout (link)
#!/bin/bash
# License: BSD License
# As Example we start 3 production processes in the background
# always record PID in PRODPID

sleep 50 &
PRODPID[1]=$!

sleep 20 &
PRODPID[2]=$!

# multiple processes in a subshell as example
(sleep 20 ; sleep 10 ; sleep 5)&
PRODPID[3]=$!

export PRODPID

# record own PID
export PID=$$


# define exit function
exit_timeout() {
  echo "Timeout. These processes are not finished:"
  for i in ${PRODPID[@]} ; do
    ps -p $i |grep -v "PID TTY      TIME CMD"
    if [ $? == 0 ] ; then
      # process still alive
      echo "Sending SIGTERM to process $i"
      kill $i
    fi
  done
  # timeout exit
  exit
}

# Handler for signal USR1 for the timer
trap exit_timeout SIGUSR1

# starting timer in subshell. It sends a SIGUSR1 to the father if it timeouts.
export TIMEOUT=30
(sleep $TIMEOUT ; kill -SIGUSR1 $PID) &

# record PID of timer
TPID=$!

# wait for all production processes to finish
wait ${PRODPID[*]}

# Normal exit
echo "All processes ended normal"

# kill timer
kill $TPID
or (link)
runtime=${1:-1m}
mypid=$
cp /Database/Client_db_200802110231.BAK .&
cpid=$!
sleep $runtime
kill -s SIGTERM $cpid
echo "Both processes are terminated".



catching traps (link)
# trap [commands] [traps]
trap "echo Booh!" SIGINT SIGTERM


aoeu
aoeu

No comments:

Post a Comment