Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting | ||
---|---|---|
Prev | Chapter 34. Miscellany | Next |
To keep a record of which user scripts have run during a particular sesssion or over a number of sessions, add the following lines to each script you want to keep track of. This will keep a continuing file record of the script names and invocation times.
# Append (>>) following to end of each script tracked. date>> $SAVE_FILE #Date and time. echo $0>> $SAVE_FILE #Script name. echo>> $SAVE_FILE #Blank line as separator. # Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc # (something like ~/.scripts-run) |
The >> operator appends lines to a file. What if you wish to prepend a line to an existing file, that is, to paste it in at the beginning?
file=data.txt title="***This is the title line of data text file***" echo $title | cat - $file >$file.new # "cat -" concatenates stdout to $file. # End result is #+ to write a new file with $title appended at *beginning*. |
Of course, sed can also do this.
A shell script may act as an embedded command inside another shell script, a Tcl or wish script, or even a Makefile. It can be invoked as as an external shell command in a C program using the system() call, i.e., system("script_name");.
Put together files containing your favorite and most useful definitions and functions. As necessary, "include" one or more of these "library files" in scripts with either the dot (.) or source command.
# SCRIPT LIBRARY # ------ ------- # Note: # No "#!" here. # No "live code" either. # Useful variable definitions ROOT_UID=0 # Root has $UID 0. E_NOTROOT=101 # Not root user error. MAXRETVAL=256 # Maximum (positive) return value of a function. SUCCESS=0 FAILURE=-1 # Functions Usage () # "Usage:" message. { if [ -z "$1" ] # No arg passed. then msg=filename else msg=$@ fi echo "Usage: `basename $0` "$msg"" } Check_if_root () # Check if root running script. { # From "ex39.sh" example. if [ "$UID" -ne "$ROOT_UID" ] then echo "Must be root to run this script." exit $E_NOTROOT fi } CreateTempfileName () # Creates a "unique" temp filename. { # From "ex51.sh" example. prefix=temp suffix=`eval date +%s` Tempfilename=$prefix.$suffix } isalpha2 () # Tests whether *entire string* is alphabetic. { # From "isalpha.sh" example. [ $# -eq 1 ] || return $FAILURE case $1 in *[!a-zA-Z]*|"") return $FAILURE;; *) return $SUCCESS;; esac # Thanks, S.C. } abs () # Absolute value. { # Caution: Max return value = 256. E_ARGERR=-999999 if [ -z "$1" ] # Need arg passed. then return $E_ARGERR # Obvious error value returned. fi if [ "$1" -ge 0 ] # If non-negative, then # absval=$1 # stays as-is. else # Otherwise, let "absval = (( 0 - $1 ))" # change sign. fi return $absval } tolower () # Converts string(s) passed as argument(s) { #+ to lowercase. if [ -z "$1" ] # If no argument(s) passed, then #+ send error message echo "(null)" #+ (C-style void-pointer error message) return #+ and return from function. fi echo "$@" | tr A-Z a-z # Translate all passed arguments ($@). return # Use command substitution to set a variable to function output. # For example: # oldvar="A seT of miXed-caSe LEtTerS" # newvar=`tolower "$oldvar"` # echo "$newvar" # a set of mixed-case letters # # Exercise: Rewrite this function to change lowercase passed argument(s) # to uppercase ... toupper() [easy]. } |
Use special-purpose comment headers to increase clarity and legibility in scripts.
## Caution. rm -rf *.zzy ## The "-rf" options to "rm" are very dangerous, ##+ especially with wildcards. #+ Line continuation. # This is line 1 #+ of a multi-line comment, #+ and this is the final line. #* Note. #o List item. #> Another point of view. while [ "$var1" != "end" ] #> while test "$var1" != "end" |
Using the $? exit status variable, a script may test if a parameter contains only digits, so it can be treated as an integer.
#!/bin/bash SUCCESS=0 E_BADINPUT=65 test "$1" -ne 0 -o "$1" -eq 0 2>/dev/null # An integer is either equal to 0 or not equal to 0. # 2>/dev/null suppresses error message. if [ $? -ne "$SUCCESS" ] then echo "Usage: `basename $0` integer-input" exit $E_BADINPUT fi let "sum = $1 + 25" # Would give error if $1 not integer. echo "Sum = $sum" # Any variable, not just a command line parameter, can be tested this way. exit 0 |
The 0 - 255 range for function return values is a severe limitation. Global variables and other workarounds are often problematic. An alternative method for a function to communicate a value back to the main body of the script is to have the function write to stdout the "return value", and assign this to a variable.
Example 34-6. Return value trickery
#!/bin/bash # multiplication.sh multiply () # Multiplies params passed. { local product=1 until [ -z "$1" ] # Until uses up arguments passed... do let "product *= $1" shift done echo $product # Will not echo to stdout, } #+ since this will be assigned to a variable. val1=`multiply 15383 25211` echo "val1 = $val1" # 387820813 val2=`multiply 25 5 20` echo "val2 = $val2" # 2500 val3=`multiply 188 37 25 47` echo "val3 = $val3" # 8173300 exit 0 |
The same technique also works for alphanumeric strings. This means that a function can "return" a non-numeric value.
capitalize_ichar () # Capitalizes initial character { #+ of argument string(s) passed. string0="$@" # Accepts multiple arguments. firstchar=${string0:0:1} # First character. string1=${string0:1} # Rest of string(s). FirstChar=`echo "$firstchar" | tr a-z A-Z` # Capitalize first character. echo "$FirstChar$string1" # Output to stdout. } newstring=`capitalize_ichar "each sentence should start with a capital letter."` echo "$newstring" # Each sentence should start with a capital letter. |
It is even possible for a function to "return" multiple values with this method.
Example 34-7. Even more return value trickery
#!/bin/bash # sum-product.sh # A function may "return" more than one value. sum_and_product () # Calculates both sum and product of passed args. { echo $(( $1 + $2 )) $(( $1 * $2 )) # Echoes to stdout each calculated value, separated by space. } echo echo "Enter first number " read first echo echo "Enter second number " read second echo retval=`sum_and_product $first $second` # Assigns output of function. sum=`echo "$retval" | awk '{print $1}'` # Assigns first field. product=`echo "$retval" | awk '{print $2}'` # Assigns second field. echo "$first + $second = $sum" echo "$first * $second = $product" echo exit 0 |
Next in our bag of trick are techniques for passing an array to a function, then "returning" an array back to the main body of the script.
Passing an array involves loading the space-separated elements of the array into a variable with command substitution. Getting an array back as the "return value" from a function uses the previously mentioned strategem of echoing the array in the function, then invoking command substitution and the ( ... ) operator to assign it to an array.
Example 34-8. Passing and returning arrays
#!/bin/bash # array-function.sh: Passing an array to a function and... # "returning" an array from a function Pass_Array () { local passed_array # Local variable. passed_array=( `echo "$1"` ) echo "${passed_array[@]}" # List all the elements of the new array #+ declared and set within the function. } original_array=( element1 element2 element3 element4 element5 ) echo echo "original_array = ${original_array[@]}" # List all elements of original array. # This is the trick that permits passing an array to a function. # ********************************** argument=`echo ${original_array[@]}` # ********************************** # Pack a variable #+ with all the space-separated elements of the original array. # # Note that attempting to just pass the array itself will not work. # This is the trick that allows grabbing an array as a "return value". # ***************************************** returned_array=( `Pass_Array "$argument"` ) # ***************************************** # Assign 'echoed' output of function to array variable. echo "returned_array = ${returned_array[@]}" echo "=============================================================" # Now, try it again, #+ attempting to access (list) the array from outside the function. Pass_Array "$argument" # The function itself lists the array, but... #+ accessing the array from outside the function is forbidden. echo "Passed array (within function) = ${passed_array[@]}" # NULL VALUE since this is a variable local to the function. echo exit 0 |
For a more elaborate example of passing arrays to functions, see Example A-8.
Using the double parentheses construct, it is possible to use C-like syntax for setting and incrementing variables and in for and while loops. See Example 10-12 and Example 10-17.
A useful scripting technique is to repeatedly feed the output of a filter (by piping) back to the same filter, but with a different set of arguments and/or options. Especially suitable for this is tr.
# From "wstrings.sh" example. wlist=`strings "$1" | tr A-Z a-z | tr '[:space:]' Z | \ tr -cs '[:alpha:]' Z | tr -s '\173-\377' Z | tr Z ' '` |
The run-parts command is handy for running a set of command scripts in sequence, particularly in combination with cron or at.
It would be nice to be able to invoke X-Windows widgets from a shell script. There happen to exist several packages that purport to do so, namely Xscript, Xmenu, and widtools. The first two of these no longer seem to be maintained. Fortunately, it is still possible to obtain widtools here.
The widtools (widget tools) package requires the XForms library to be installed. Additionally, the Makefile needs some judicious editing before the package will build on a typical Linux system. Finally, three of the six widgets offered do not work (and, in fact, segfault). |
For more effective scripting with widgets, try Tk or wish (Tcl derivatives), PerlTk (Perl with Tk extensions), tksh (ksh with Tk extensions), XForms4Perl (Perl with XForms extensions), Gtk-Perl (Perl with Gtk extensions), or PyQt (Python with Qt extensions).