Basics of UNIX shell scripts

With UNIX scripts you can do many powerful things. You won’t be able to take over the world with it, but it’s pretty close. Scripts can be useful to automate a set of tasks or to perform some more complicated actions.

Many UNIX applications come with a set of scripts, such as Oracle DB, JBoss AS, Tomcat, ANT, etc. Even the OS itself contains a lot of scripts. Each time you log in, scripts such as .profile, .cshrc, .bashrc, … are executed automatically when they are located in your home directory and you are running the appropriate default shell (indicated in /etc/passwd).

Here’s a simple example:

This script shows some of the most basic things you can do. Here is what each line does:

1: Invokes the specified shell, in this case /bin/sh. Other examples are /bin/ksh, /usr/bin/tcsh, etc. If the shell does not exist you will get an error similar to “bad interpreter: No such file or directory” and the script will exit.

2: Comments begin with the # character.

3: This if-statement compares the numeric value $# against the value 0. $# indicates the number of arguments the user specified to this script. For instance if the script is called bogus.sh and it was executed as ./bogus.sh hi there, then $# would have the value 2. In addition, variable $0 is equals to “./bogus.sh”, $1 is equal to “hi” and $2 would be “there”. Be aware of the space before and after each square bracket!

4: Writes the specified text to the standard output (console).

5: Exits the script.

6: This else-if statement is true if the string value of $# is equal to “1”.

11: Sets variable “tempfile” to the specified value. $$ is substituted by the process id (PID) of the script at the time, which is system unique at the time of creation.

12: The 2 commands on this line are separated by semicolon. The 1st one runs the pwd command (get current directory) and assigns its value to variable “here”. The 2nd one changes the current directory to /home.

13: For-loop that iterates over each file in the current directory (/home).

14: If-statement is true if the current file is a directory.

15: Backslash at end indicates that command continues on next line.

16: Append output of preceding command to the file specified by the “tempfile” variable.

21: End of loop.

22: Change directory back to the original one.

23,25: While-loop, one iteration for each line of the file specified by “tempfile”.

24: Alternative way to output text besides the echo command.

25: Delete the temp file without asking permission. The 2> redirects errors to the specified location, which can be a file, or to the garbage, which is /dev/null (NUL in DOS).

Leave a Reply

Your email address will not be published. Required fields are marked *

*