2.20. Shell Flags and Variables

Unix shells have many command line flags to control their behavior.

One of the most popular shell flags is -e. The -e flag in both Bourne Shell and C shell cause the shell to exit if any command fails. This is almost always a good idea, to avoid wasting time and so that the last output of a script shows any error messages from the failed command.

Flags can be used in the shebang line if the path of the shell is fixed. When using #!/usr/bin/env, we must set the option using a separate command, because the shebang line on some systems treats everything after '#!/usr/bin/env' as a single argument to the env command.

#!/bin/sh -e

# The shebang line above is OK
	
#!/bin/csh -e

# The shebang line above is OK
	
#!/usr/bin/env bash -e

# The shebang line above is invalid on some systems and may cause
# an error such as "bash -e: command not found"
	

We can get around this in Bourne family shells using the set command, which can be used to turn on or off command-line flags within the script. For example, "set -e" in a script causes the shell running the script to terminate if any subsequent commands fail. A "set +e" turns off this behavior.

#!/usr/bin/env bash

# Enable exit-on-error
set -e
	

Unfortunately, C shell family shells do not have anything comparable to the Bourne shell set command. Recall that C shell has a set command, but it is use to set shell variables, not command-line flags.

Many features controlled by command-line flags can also be set within a C shell script using special shell variables, but -e is not one of them.

The -x flag is another flag common to both Bourne Shell and C shell. If causes the shell to echo commands to the standard output before executing them, which is often useful in debugging a script that it failing at an unknown location.

#!/bin/sh -x
	
#!/bin/csh -x
	
#!/bin/sh

set -x      # Enable command echo
command
command
set +x      # Disable command echo
	
#!/bin/csh

set echo    # Enable command echo
command
command
unset echo  # Disable command echo
	

As stated in Section 2.6, “Shell Start-up Scripts”, Bourne shell family scripts do not source any start up scripts by default. Bourne shells only source files like .shrc, .bashrc, etc. if the shell is interactive, i.e. the standard input is a terminal.

C shell and T shell scripts, on the other hand, will source .cshrc or .tcshrc by default. This behavior can be disabled using the -f flag. Disabling this is usually a good idea, since the script may behave differently for different people, depending on what's in their .cshrc.

#!/bin/csh -ef
	

There are many other command-line flags and corresponding C shell variables. For more information, run "man sh", "man csh", etc.