The Non-interactive Shell

When reading from a script or other input source that is not an interactive terminal, the shell automatically runs in non-interactive mode. In this mode, several behaviors are modified, and the shell does not:

  • Print a prompt message before reading each line of input, nor does it specially interpret command-line editor meta-characters such as the arrow keys , , , and .

  • Maintain a command history of previous commands

  • Print informative diagnostics when background jobs are executed or change state

  • Catch and specially handle various signals that would be generated by user input in an interactive terminal, such as SIGINT, SIGQUIT, SIGTERM, etc.

Aside from the behavioral changes mentioned above, the shell behaves essentially the same in an interactive and non-interactive context. All of the features of the language we will cover apply equally to both, and many examples will demonstrate these non-interactive features within an interactive context. However, as we will quickly notice, many of the language features used in shell scripting range from unwieldy and awkward to pointless in an interactive context, so they are used rarely outside of scripting contexts.

Writing and Executing a Shell Script

A shell script is a file containing shell commands which are interpreted and executed by the shell identically to how it processes interactive input. The following example creates a simple shell script that contains the command “echo Hello World!” and executes it:

$ printf 'echo Hello World!\n' >hello-world.sh
$ sh hello-world.sh
Hello World!

Shell scripts can be simple, containing only a few lines as shown above, but they can also be used to write complex programs that perform a variety of tasks.

When the shell is invoked with a shell script as shown, it opens that file separately, retaining its inherited standard input, output, and error streams. This allows shell scripts to interact with the user or other input sources without mixing up commands with input. This is subtly different from if the script were instead passed in on standard input ($ sh < hello-world.sh). In such a case, any commands that read input would consume the rest of the script as input instead of reading from a separate input source!

Hallmarks of a Shell Script

As mentioned above, all of the features we will cover are available interactively, but have little use outside of shell scripts. The main hallmarks of a shell script vs interactive use are the extensive application of:

  • positional and special parameters

  • control-flow constructs using familiar keywords like if, for, while, and shell functions.

  • shell special and regular builtin utilities