fnc() { local x="this variable is local in scope to this function" echo $x } passf() { # use local for safety, but will not be avail outside script... #local user #local pass echo -n "username: " read user stty -echo echo -n "password: " read pass stty echo echo -e "" } passf_do() { passf echo $user echo $pass } #---------------------------------------------------------------------------- demonstrate use of awk method #returns days in month monthd() { local monthd="31 28 31 30 31 30 31 31 30 31 30 31" echo "$monthd" | awk '{ print $'"${1}"' }' } ; #monthd $1 # demonstrate use of stdin to function stdinf() { while read line; do echo "$line" | grep $1 | awk -F":" '{ print $5 }' # Have awk use ":" delimiter. done } </etc/passwd #$file # redirect into function's stdin. #pattern=gnats #stdinf $pattern # $1 #---------------------------------------------------------------------------- dereferencing a parameter passed to a function dref() { y=\$"$1" # name of variable #echo $y # $xvar x=`eval "expr \"$y\" "` echo $1=$x eval "$1=\"new text \"" # assign new value } dref_do() { xvar="just text" echo $xvar "before" # just text before dref xvar echo $xvar "after" # Some Different Text after } #---------------------------------------------------------------------------- Indirect References to Variables Of what practical use is indirect referencing of variables? It gives Bash a little of the functionality of pointers in C, for instance, in table lookup. Indirect references also allows building "dynamic" variable names and the ability to evaluate their contents which can be useful when sourcing configuration files. Bash does not support pointer arithmetic, and this severely limits the usefulness of indirect referencing. indirect references can be accomplished with two different methods: 2) eval \$$x - bash v1 and up 1) ${!x} - bash v2 and up passing an indirect reference to a function echof() { r=$1 echo "$r" } indirect_ref() { x=y y=z echof "$x" #: y echof "${!x}" #: z echo "${!x}" #: z } dynamic variable name generation using indirect references dynvar() { dyn=dynvar_$1 # create dynamic variable handle eval "$dyn=x" # assign value to dynamic variable echo $dyn #: dynvar_xyz - direct reference. echo ${!dyn} #: x - indirect reference. #alternate method: eval a=\$$a eval echo \$$dyn #: x - indirect reference. eval dyn=\$$dyn #: change handle to hold the value. echo $dyn #: x - indirect reference. } dynvar xyz