Skip to end of metadata
Go to start of metadata

The general structure of a shell script (start off each script with a shebang).

Creating a shell script file

  • Shell scripts should begin with a 'shebang'. Usually

    or

    .

  • To make the script executable, simply

  • File extensions don't matter in Linux and Unix. You can name the script 'myscript.sh' or just 'myscript' and it will make no difference, other than the fact that you will have to type the whole file name to execute it.
  • Shell scripts must use Unix/Linux-style line feeds! Even under Cygwin this is true. To convert a shell script file to Unix line feed format, use dos2unix.

Common preamble

You can define a few useful shell variables at the beginning of every script:

Notes:

  • $BASH_SOURCE[0] is the path to the script.   You could use $0 instead, but when the script is run with the source command this can lead to unexpected results.
  • You can also use SCRIPT_DIR=`dirname $BASH_SOURCE[0]`, but this would result in a relative path.   Adding `cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd` gives you the absolute path.
  • See this SO question for more details.

Strict mode

Another common technique for Shell scripting is to enable strict variable checking. This will cause the script to fail if a variable is referenced before it is defined, which can often cause bugs.

To enable strict mode, use:

Then, if you do need to reference a variable before it is defined, use:

or

See Also