Category Archives: Shell

Shell scripting

There are many shells available like bash, dash, ash, csh. Bash (Bourne Again Shell) is the richest with features but at the same time also big (combiled image in my system about 1 MB) and sometimes also slow. Therefore Debian and many derivatives (Ubuntu, Mint, …) use dash as the startup shell. Dash is smaller (compiled image size about 0.12 MB in my Ubuntu based system).

If you want to see the source code of the shell you can get it in Debian and derivatives with commands (following gets the source of bash)

Remember that you should not use sudo when getting the source code.

Next to the scripting itself. The scripts can be driven from the command line like

You can make a very simple Hello World script with editor and save it as test.sh

And you can run it on the command line

By adding to the script #!/bin/bash #!/bin/bash

you can call the script directly by giving the execute rights with chmod

Variables can be defined like variable_name=”some text” or in the case of numbers or single words variable=1 (without quotation marks). There are some predefined variables like PWD which means current working directory. When you are using the variables you have to use $-sign before the variable. Example

prints your current working directory.

Conditions. If then -structure.The test will be made inside of brackets [ ]. The structure is ended with fi.

Below we will test if some port is open with a netcat program. nc – z localhost 22 test if the port is open. The return value is stored in $? variable. If it is open the return value is 0 otherwise something else.

For-loop. We test now if some port is open. This is basically a very simple netstat.

It is usually a very good habit to try to keep the shell scripts as portable as possible between different shells. There is a command line tool called checkbashism available to chech if you have used something that would work only on bash.

Some topics to cover

  • If you want to read variables you can used read-function.

There are books on shell scripting