6.4.2010

bash tips & tricks

Filed under: Linux,Unix — nax @ 19:19

Recently I am in need to repeat bash scripting and may be to learn something new. There are some nice features which surprised me, because I have never saw them in action, I haven’t know them.

Just for record, I use Unix Shell by Example by Eliie Quigley.

variables

variable=${variable:-word} If variable is set and is non-null, substitute its value; otherwise, substitute word. This can be very easily set just unset variables. It is equivalent of:

if [ ".$variable" = "." ] ; then 
   $variable = "word";
fi

${variable:?word} If variable is set and is non-null, substitute its value; otherwise, print word and exit from the shell. If word is omitted, the message parameter null or not set is printed.

if [ ".$variable" = "." ] ; then 
   echo "word";
   exit
fi

${variable:offset:length} Something as a substring() function in other programing languages. You can omit length parameter.

read & arrays

You can give your user command line editing functions (let say with vi editor commands) while using read command:

read -e variable

Do you know that read command can be used also to read elements to an array?

read -a arrayname

You can address fields in array like this: ${arrayname[2]}. To declare an array you can use keyword declare with same parameter (-a):

declare -a fibonaci=(1 1 2 3 5 8 13)

or just declare it with parenthesis:

fibonaci=(1 1 2 3 5 8 13)

BTW, you do not need to declare in right order, or you can even omit some slot:

fibonaciwtf=(1 [6]=13 2 [1]=1)
for element in `seq 0 6`; do 
   echo $element=${fibonaciwtf[$element]}
done

0=1
1=1
2=
3=
4=
5=
6=13

parsing parameters

while getopts xy options; do
   case $options in
        x) echo "you entered ??x as an option"
            ;;
        y) echo "you entered ??y as an option"
            ;;
   esac
done

Another great source is Advanced Bash-Scripting Guide from tldp.org

Comments are closed.

Powered by WordPress