Shell script
A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. Shell scripts are used to automate sequences of commands, system administration tasks, and to combine existing utilities into more powerful tools. They are often written in scripting languages such as Bash, sh, zsh, or ksh.
Shell scripts are plain text files that contain one or more shell commands along with control structures like loops and conditionals. They are typically invoked by specifying the path to the script or by the shell's source command. A common feature is the shebang (#!) line at the top, which tells the operating system which interpreter to use.
History
The first Unix shell, the Thompson shell, was developed in the early 1970s by Ken Thompson. It lacked scripting capabilities beyond simple command chaining. The Bourne shell (sh), introduced with Version 7 Unix in 1979, added variables, control flow, and subroutines, enabling full scripting. The Bourne shell became the standard scripting environment for Unix. Later, the GNU Project developed Bash (Bourne Again SHell) in 1989, which extended the Bourne shell with features from the C shell and KornShell. Bash became the default shell on many Linux distributions and macOS (until 2019). Other notable shells include Z shell (zsh), fish, and KornShell (ksh).
Features
- Interpreted execution: Shell scripts are executed line by line by the shell interpreter, not compiled.
- Shebang line: Typically the first line, e.g.,
#!/bin/bash, defines the interpreter. - Variables: User-defined and shell environment variables, with simple substitution (
$var) and parameter expansion. - Control structures:
if,for,while,case, and functions (in most modern shells). - Command substitution: Embedding output of commands using backticks or
$(). - Pipelines and redirection: Combining commands with
|and redirecting input/output streams. - Portability: POSIX-compliant scripts (using
sh) run across most Unix-like systems; Bash scripts often require Bash-specific extensions. - Common interpreters: Bash, sh, zsh, ksh, dash (for lightweight POSIX scripting).
Shell scripts are widely used for system startup scripts, package maintenance, logging, and automation in DevOps pipelines. They are also a common tool for system administration and repetitive task automation.
While powerful, shell scripts can be error‑prone due to subtle quoting rules, whitespace sensitivity, and non‑standard behavior across different shells. Best practices include using set -e to exit on errors, quoting variable expansions, and preferring printf over echo for portability.