BASH Shell Script Examples. If Then Statements. ~~~~~~~~~~~~~~~~~~~ if [ test1 ] # See 'man test' for the varous tests to place between the [ ]. then command 1 elif [ test2 ] then command 2 else command 3 fi Case statements. ~~~~~~~~~~~~~~~~ case $VAR in match1) command 1 ; command 2 ;; match2) command 3 ; command 4 ;; match3) command 5 command 6 ;; *) echo "Invalid." ;; esac LOOPS ~~~~~ 'for' LOOP ~~~~~~~~~~ for I in Item1 Item2 Item3 ... do echo $I command 1 command 2 done The items listed can be defined in a variable. LIST="Item1 Item2 Item3" for I in $LIST do ... Additionally brace expansion can be used for sequences. for I in {0..9} {a..z} {A..Z} do ... this will expand out to all 10 numeric digits and the full alphabet in lower and upper case. 'while' LOOPS ~~~~~~~~~~~~~ The while true infinite loop. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while true # : can be used in place of true do command 1 command 2 command 3 [ -n "$VAR" ] && break done The while test is true loop. ~~~~~~~~~~~~~~~~~~~~~~~~~~ while [ test is true ] # see man test for the varous tests to place between the [ ]. do command 1 command 2 command 3 done The while read line loop. ~~~~~~~~~~~~~~~~~~~~~~~~~ echo "Line One Line Two Line Three Line Four Line Five" | while read line do echo $line done until LOOP - Until test is true. ~~~~~~~~~~~~ until [ test is true ] # see 'man test' for the varous tests to place between the [ ]. do command 1 command 2 command 3 done Functions ~~~~~~~~~ function_name() { command 1 command 2 command 3 return } Source a file ~~~~~~~~~~~~~ . /Full/Path/to/a/File or source /Full/Path/to/a/File Variables ~~~~~~~~~ Setting a variable. VAR="This is a String" Retreiving the contents of a variable. echo "$VAR" Placing the contents of one variable into another. VAR2="$VAR" Placing the output of a command into a variable. VAR2=`command opt1 opt2 | command2 opt3 opt4` or VAR2=$(command opt1 opt2 | command2 opt3 opt4) Exporting variables so programs called from script will inherit variable and its contents. export VAR Redirection ~~~~~~~~~~~ Standard out is placed in 'fileout' and previous contents are overwritten. command > fileout Read contents of 'filein' into command. Output is sent to standard out. command < filein Both commands above combined. command < filein > fileout Standard error is placed in 'fileout' and previous contents are overwritten. command 2> fileout Adding '2>&1' after 'fileout' will also place standard error in 'fileout' also. command > fileout 2>&1 Common use is to direct all output of command to the garbage. command > /dev/null 2>&1 Standard out is appended to 'fileout' command >> fileout Standard error is appended to 'fileout' command 2>> fileout Both standard out and standard error are appended to 'fileout' command >> fileout 2>&1 Sending standard out to standard error. command >&2 The Here File. Read input until you get to here (EOF). command << EOF This is text that is to be read into 'command' EOF Where 'command' could be cat, more, less or any command that reads from standard in. Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ Using a while loop to cat a here file to avoid a system call. while read line ; do echo "$line" ; done < output_file For reading and writing. exec N<> file Rreading from. command <&N Writing to. echo string >&N Closing. exec N<&- The most used exampe is: exec 3> /tmp/file.$$ # Open handle echo "String 1" >&3 # \ echo "String 2" >&3 # > Output commands into handle echo "String 3" >&3 # / exec 3<&- # Close handle process /tmp/file.$$ rm /tmp/file.$$ The file /tmp/file.$$ will contain all strings printed to it while handle is open. Once closed the file can be processed. $$ will be replaced with the process ID of the script. '3' is the 1st file descriptor available after stdout(1) & stderr(2). Useful ASCII Codes ~~~~~~~~~~~~~~~~~~ Disp Dec Character In a Terminal & VI  27 ESC Escape sequence ^\ 28 FS File separator Use with caution.  29 GS Group separator  30 RS Record separator  31 US Unit separator For the full ascii code list see 'man ascii' Most robust in linux. These can be used in script databases. The US can be used as a separator in a sed subtitution string ensuring that no regular character introduced through a variable in the subtitution string will conflict with with the operation. Special variables. ~~~~~~~~~~~~~~~~~~ Expands to the positional parameters, starting from one. $* - When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character. $@ - When the expansion occurs within double quotes, each parameter expands to a separate word. $# - Number of arguments given on command line. $? - Error level exit status of previous command run. $$ - The process ID of the current shell. $0 - Full path and name of current script. $1 - First argument for current script. $2 - Second argument for current script. $3 - Third argument for current script. (And so on) ANSI Formatting ~~~~~~~~~~~~~~~ Formatting strings are enabled with the following syntax: Movement codes: ESC[#@ Where: #=number, @=alpha char. #A - Cursor Up # Lines. #B - Cursor Down # Lines. #C - Cursor Forward # Characters. #D - Cursor Backward # Characters. #E - Cursor to Beginning of # Lines Down. #F - Cursor to Beginning of # Lines Up. #G - Move Cursor to Column #. #,#H - Move Cursor to Row#,Column# . #J - Erase Data. Where #: 0=from cursor to end of screen, 1=from cursot to beginning of screen, 2=clear entire screen move cursor to 0,0. #K - Erase in Line. Where #: 1=clear to end of line, 2=clear entire line. #S - Scroll Up. Scroll up page by # lines. #T - Scroll Down. Scroll down page by # lines. Lowercase 'M' | Format: ESC[#;#;#m | | Open + - Semicolon allows multiple codes in one command. Square Bracket Where: 'ESC' Is the escape character. In 'vi' insert using or and will display as ''. '#' Is one of the numbers/codes below. In 'vi': Bold:  Bold Green text, black background:  Yellow text, red background:  Cancel all codes:  0 - No formatting. 1 - Bold. 2 - Faint. 3 - Italic. 4 - Underline. 5 - Blink Slow. 6 - Blink Fast. 7 - Reverse. (Swap background & text colors.) 8 - Conceal. (Hide any letters typed or displayed.) 9 - Strike Through. 10 - Primary (default) Font. 11-19 N-th Alternate Font 20 - Fraktur 21 Double Underline 22 - Normal Color/Intensity 23 - Not Italic, Not Fraktur. 24 - Underline Off. 25 - Blink Off. 26 - Reserved. 27 - Image: Positive. 28 - Reveal. 29 - Strike Through Off. Text Color Background ------------------------ 30 - Black - 40 31 - Red - 41 32 - Green - 42 33 - Yellow - 43 34 - Blue - 44 35 - Magenta - 45 36 - Cyan - 46 37 - White - 47 38 - Reserved 39 - Default text color. 48 - Reserved 49 - Default background color. 50 - Reserved. 51 - Framed 52 - Encircled 53 - Overlined 54 - Cancel Framed, Enciricled. 55 - Cancel Overlined. 56-59 Reserved 60 - Ideogram underline or right side. 61 - Ideogram double underline on the right side. 62 - Ideogram overline on left side. 63 - Ideogram double overline on left side. 64 - Ideogram stress marking. Help Info - Display help message when '-h' or '--help' is only given as argument. ~~~~~~~~~ if [ "$1" = -h -o "$1" = --help ] then if [ -f /usr/bin/less ] then PAGER="/usr/bin/less -fgr -x 4" else PAGER=more # Or 'cat' if help is small. fi $PAGER << EOH script_name - This is a shell script to do something. Usage: script_name [opt1 opt1 opt3] Arguments - Format opt=value opt1 - This is option 1. opt2 - This is option 2. opt3 - This is option 3. More descriptions, etc.... EOH exit 1 fi Command Line Parsing. ~~~~~~~~~~~~~~~~~~~~~ while [ $# -gt 0 ] do ARG=`echo "$1" | cut -d = -f 2-` case $1 in opt1=*) OPT1="$ARG" ;; opt2=*) OPT2="$ARG" ;; opt3=*) OPT3="$ARG" ;; *) echo "Invalid Argument: ${1}." ;; esac shift 1 done Prompt for User Input. ~~~~~~~~~~~~~~~~~~~~~~ # Function the process a string from user input. # # If REQ is set to 'y' then the function will # not return until the user enters data. # Entering 'clear' will clear previous setting. # Set the maximum length of the prompt string. Max=50 getString() { while : do printf "% ${Max}b" "$PROMPT " if [ -n "$STRING" ] then printf "[${STRING}] : " read string if [ "$string = clear ] then unset STRING elif [ -n "$string" ] then STRING=$string fi else printf "[] : " read STRING fi if [ "$REQ" = Y -a -z "$STRING" ] then printf "\e[1m Required Field. You Must Enter Data.\e[0m\n" else break fi done unset PROMPT string REQ } # Test if set from command line otherwise prompt user for string. for Var in OPT1 OPT2 OPT3 do # Required? Default Prompt Message case $Var in OPT1) REQ=Y ; STRING="One" ; PROMPT="Enter value for option 1" ;; OPT2) REQ=N ; STRING="Two" ; PROMPT="Enter value for option 2" ;; OPT3) REQ=Y ; STRING="Three" ; PROMPT="Enter value for option 3" ;; esac eval val=\$$Var if [ -z "$val" -a "$REQ" = Y ] then getString eval $Var=\$STRING fi done Select from list ~~~~~~~~~~~~~~~~ select F in Apples Ornages Bananas Strawberries Blueberries Watermelon do Fruit=$F break 1 done A list will be presented to select from: 1) Apples 2) Ornages 3) Bananas 4) Strawberries 5) Blueberries 6) Watermelon #? At the #? prompt enter the associated number and the item selected will be set in the $Fruit variable. Reformatting date command output for readability and file naming. c=0 ; for d in $(date) ; do ((c++)) ; eval d$c=\$d ; done DATE="$d1 $d3 $d2 $d6 - $d4 $d5" ; date="${d1}${d3}${d2}${d6}" unset c d d1 d2 d3 d4 d5 d6 ---------------------- ©2010 - J. S. Gilstrap