5 Things to know before starting scripting in Bash Shell

#1 Command Lifecycle

When a command is given to the shell, the interpreter does the following main steps:

  1. Variable substitution — replaces all variables with their values
  2. Line parsing — the interpreter re-scans again the line and trims additional spaces between arguments+ parses special chars
  3. Command execution — Executes given command
Output from lifecycle.sh script
  1. First the shell replaces the $ahah variable with it’s initial value
  2. Then, it re-scans the line and because the value of $ahah is not quoted, it trims all the additional spaces (resulting in “Several spaces *”) and finally it parses the special char “*”, that in this case, lists all the files of the current directory, separated by a space
  3. Finally echo is executed with the following arguments: “Several”, “spaces”, “lifecycle.sh” and “phones.txt

#2 Every variable is a string!

In Bash every variable is treated as a string! That’s why the following script outputs “Not Equal”:

#3 [ is a command

A funny fact about the Bash is that [ is an actual command. Test this out:

#4 Don’t loop over $*

Looping over $* almost always means bug! Check what happens when the argument given has spaces (second run):

#5 Use -x option for debugging

We all know that traditional echo commands can be handy for debugging, but most of the times the -x option can make things easier! Take a look of what happens when we enable this option:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
André Gil

André Gil

Computer Engineer with a fascination for books, Linux, security and the AI field.