best practices in shell script programming – double quotes

You do know the result of this:

a=A; echo $a

But are you just as sure here?

a=A; b=B; echo $a.$b

That depends on the shell, you are using. So I suggest you better write it this way:

a=A; b=B; echo ${a}.${b}

Enclosing variable names in curly braces is quite often a good idea.
Look at the following piece of code:

case $var in

  x*)

    echo var starts with x

    ;;

  *)

    echo var starts with something else

    ;;

esac

Looks alright, doesn’t it?
No, it’s does not. If that variable had not been assigned a value before or is of zero length, you will see an ugly syntax error occur.
Therefore enclose the variable in double quotes like here:

case “$var” in

  x*)

    echo var starts with x

    ;;

  *)

    echo var starts with something else

    ;;

esac

There is no good excuse for not doing it anywhere. It may look ugly and unnecessary, but it will help. That’s the way shell scripting is. I learned this from Jürgen Gulbins around 1987, when I enjoyed working for him. This series of articles is dedicated to him. I owe him a lot.

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.