Introduction To Bash Shell Scripting

References

Review

Shell Variables

Some Command Useful With Scripts

Making Scripts Colorful

Shell Functions and Scripts

Operation With Variables

  • Test Operation

  • String Operation

  • Pattern Operations

    The handy 'expr'

    Flow Control

  • break/continue

    • break [n] Break out of loop & select
    • continue [n] Continue next iteration of loop
  • case

      case expression in
        pattern1[|pattern11] } statements ;;
        pattern2[|pattern21] } statements ;;
        ...
      esac
      

    User Interfaces

  • select

      select name [in list] do
        statements that can use $name
      done
      
    • Generate a menu of each item in the list formatted with a number for each choice
    • Prompt the user for the number
    • Store the selected choice in name. The number is stored in REPLY
    • execute the statements in the do
    • Repeat the process again

    Command Line Options

    • shift Shift 1st argument form the argument list
    • getopts Used to process command line options
    • OPTIND Variable contains number of options
    • OPTARG Default variable for option
    • Example while getopts ":ab:c" opt; do case $opt in a) process_option_a;; b) process_option_b $OPTARG is the option's argument;; c) process_option_c;; esac done shift $(($OPTIND - 1))

    I/O in Scripts

    • printf Built-in command for formatted output
    • read Built-in command to read one line into variable(s) read #Everything entered goes to REPLY read var #Everything is read into var read a b #Read 1st word in to a and rest into b read -t 300 var #Read with 300 second timeout
    • Example how to use read from $file while read line; do do_something_with_line done <$file

    Process Handling

    • Signals

        Name  Number  Control Character
        
      • EXIT 0 Used to trap exiting script
      • HUP 1 Logout
      • INT 2 Control-C
      • QUIT 3 Control-\
      • KILL 9 can not be ignored or trapped
      • TERM 15 Default kill
      • TSTP 24 Control-Z
    • Traps

      • trap "" signal-list Ignore signal
      • trap "cmds" signal-list Execute commands if signal is caught
      • trap signal-list Reset signal to original condition
      • trap : signal-list (undocumented) ignore signal, pass to child Signal are normally not passed to subprocesses
      • Examples trap 'rm tmpfile; exit' 0 1 2 #remove tmpfile on exit, logout, interrupt trap "echo 'You hit Control-C'" INT while true ; do sleep 60 done
      • Example parent child process #!/bin/bash #parent echo parent running trap 'echo parent exiting; exit' 0 trap :2 child sleep 1000 #!/bin/bash #child echo child started. pid is $$ trap 'echo child got signal 2; exit' INT sleep 1000

    Examples Useful Scripts or Function

      
      
    • # Function top5 Example how to set defaults # Usage top5 {n} #list n processes function top5 { ps -ef | head -${1:-5} }
    • # Function hereis Example of HERE IS FILE and handling arguments # Usage hereis word1 word2 ... function hereis { for name in "$@" do cat <<MSG This is an example of an HERE IS FILE. One argument is ${name}. The date is `date`. MSG done }
    • # Function pick Return selected items by user # Usage: .e.g var=`pick *` function pick { for name in $@ ; do #for each item in argument list echo -n "$name (y/n/q)?" >/dev/tty #ask user to select read ans #read answer from standard in case $ans in #Check choices y*) echo $name;; #selected q*) break;; #skip rest of arguments *) continue;; #skip item esac done }
    • # Function acal Display a nicer calendar # but will accept Alphabetic month function acal { m="" case $# in 0) cal; return;; #no arguments 1) m=$1; y=`date +%Y`;; #1 argument 2) m=$1; y=$2;; #2 arguments esac case $m in Jan*|jan* ) m=1;; Feb*|feb* ) m=2;; Mar*|mar* ) m=3;; Apr*|apr* ) m=4;; May|may } m=5;; Jun*|jun* ) m=6;; Jul*|jul* ) m=7;; Aug*|aug* ) m=8;; Sep*|sep* } m=9;; Oct*|oct* ) m=10;; Nov*|nov* ) m=11;; Dec*|dec* ) m=12;; [1-9]|1[0-2] ) ;; #numeric month *) ) y=$m; m="";; esac cal $m $y }
    • ## Function selectex - Example select # function selectex () { choices="/bin /usr /home" select selection in $choices; do if [ $selection ]; then ls $selection break else echo 'Invalid selection' fi done }
    • # Function fwhich Which command in $PATH is executed # function fwhich { if [[ $# -eq 0 ]] ; then cat << EndOfHelp 1>&2; return 2 Usage fwhich command #Example of parsing the $PATH Return 0 - found Return 1 - not found Return 2 - No arguments EndOfHelp fi for path in `echo $PATH | sed 's/^:/.:/ s/::/.:/g s/:$/:./ s/:/ /g'` do if [[ -x $path/$1 ]] ; # does executable file exists here? then echo $path/$1 # found it return 0 fi done return 1 # not found }
    • # Name: overwrite Copy standard input to output after EOF function overwrite { if [[ $# -lt 2 ]] ; then echo "Usage: overwrite file command [args]" 1>&2; return 2 fi file=$1; shift new=/tmp/overwrite1$$; old=/tmp/overwrite2$$ trap 'rm -f $new $old; return 1' 1 2 15 # clean up files "$@" > $new if [[ $? -eq 0 ]] ; # collect output then # command completed successfully cp $file $old # save original file trap '' 1 2 15 # we are committed; ignore signals cp $new $file # copy new file into file rm -f $new $old # remove temp files else echo "overwrite: $1 failed, $file unchanged" 1>$2 return 1 fi }
    • # Name: zgrep # Purpose: caseless grep of gzip files # Usage: zgrep text files.gz # function zgrep { if [ $# -eq 0 ] ; then echo "Usage: zgrep grep_text files.gz" return 2 fi text=$1 shift while [ $# -gt 0 ] do echo $1 gzip -cd $1 | grep -i $text shift done }
    • # Name: hgrep # Purpose: highlighting grep # Usage: hgrep pattern files # function hgrep { if [ $# -lt 2 ] ; then echo "Usage: hgrep pattern files" return 2 fi pattern=$1;shift sep=$'\001' #note use of $' ' to create control characters bold=$'\e[1m'; off=$'\e[0m' underline=$'\e[4m'; reverse=$'\e[7m' #other choices of highlighting sed -n "s${sep}${pattern}${sep}${reverse}&${off}${sep}gp" $* }