Simple tutorial for programmers writing a Bash script

Continuing with my teach by example methods the following examples show how to write a Bash script. They build upon each other to produce more and more complex scripts.

Bash is a free software Unix shell written for the GNU Project. Its name is an acronym which stands for Bourne-again shell, a pun on the name of the Bourne shell (sh)

I assume you know how to create a text file. I still prefer vi, but anything works that results in a text file.

Let's start with a script which outputs a line of text to the console

-bash-3.2$ vi bash.ex
-bash-3.2$ cat bash.ex
echo "Hello. This is a line of text"
-bash-3.2$ chmod +x bash.ex
-bash-3.2$ ./bash.ex
Hello. This is a line of text

The above shows that we used vi to create a file bash.ex. The contents were verified with the cat command so as to display the file contents to the console. The permission on the file was changed with chmod +x bash.ex to include the ability to execute the file. Finally, the script in bash.ex was run by invoking the command ./bash.ex

The next step is to take input from the command line and include it in the script. Up to 9 variables can be passed from the command line to the script. They are contained in the variables $1 through $9. The number of variables is contained in $# and the entire string is within $*

-bash-3.2$ cat bash.ex
echo "Hello $1. This is a line of text"
-bash-3.2$ ./bash.ex Tony
Hello Tony. This is a line of text

What changed above is that the $1 was added after Hello. $1 is a variable which contains the first parameter on the command line. When entering the execution command also type a parameter after a space. That parameter will then be displayed in the output.