Skip to end of metadata
Go to start of metadata

Other Pages

One liners

See Shell One Liners

Shell Programming

Start with a shebang!

See Start off with a shebang

Launching a nested shell from a shell script

Nested shells can be really useful for setting up environment variables, PATH, and LD_LIBRARY_PATH in a clean way. You could just source in a shell script that sets environment varaibles, etc, but in the nested shell it is much easier to return to the un-touched environment by typing exit.

Cygwin compatibility

If you are using Cygwin, you need to do a few extra things to 'path names' and other structures before invoking non-Cygwin commands. ANT is a good example because it is run under Java, which doesn't know about Cygwin paths.

Here is an example of setting ANT_HOME from a shell script:

Of course, this won't work on Linux, so it could be made more portable like this:

Note:

  1. PATH is not converted. That's because Cygwin uses PATH.
  2. JAVA_HOME and ANT_HOME are converted 'after' PATH is set because ant doesn't know about Cygwin's path system, but Cygwin bash does.

Script name and script path

See Start off with a shebang

Relative to absolute path names

To get the absolute path name from a relative path name:

Note that the 'cd' command inside the back-ticks does not affect the current directory of the running script.

To get the full path of the parent directory of the current script:

Here Documents

You can avoid creating temporary files in shell scripts by using 'here documents' (covered in the redirections section of the Bash reference manual).

A simple example:

Some common uses of here documents:

Shell Gotchas

Common shell programming mistakes.

Boolean Logic Expressions - equality, AND, OR

Boolean logical expressions, in if and while statements for example, are a little different in shell. A Java programmer might be tempted to write:

This will normally produce a [: missing `]' error because && was used for a logical AND instead of -a. The correct code is:

Operation

Other Languages

Shell expression operator

Logical AND

&& (Java and C++), AND

-a

Logical OR

|| (Java and C++)

-o

Equals

== (Java and C++)

-eq

Test for Empty / Non-empty String

You can use -z and -n to test for empty string and non-empty string, respectively.  There are two gotchas here:

  1. When testing the value of an environment variable, it must be enclosed in quotes.
  2. When using 'strict mode' (set -u), environment variables that have not yet been set must be inside a conditional expression.

Surrounding the environment variable in quotes:

Using a conditional expression and also surrounding the variable in quotes:

Labels