Introduction
A shell script is a text file of commands for a Unix shell, the program that reads what is typed at a terminal. The Bourne shell of 1979 set the pattern. The KornShell, Bash and Zsh extended it, and POSIX standardised a common core.
The extension is only a convention, and many scripts have none. .sh is the
general name, usually for a script that any POSIX shell can run, while
.bash, .zsh and .ksh mark scripts written for one
shell.
Structure
A script is plain text with Unix line ends. The first line is often a shebang such as
#!/bin/sh or #!/usr/bin/env bash, which tells the system which
program should run the file when it has execute permission. A carriage return at the end
of a line, from a file saved on Windows, becomes part of the last word on that line and
breaks the script.
Each line is a command and its arguments, split on spaces. Commands connect with
|, && and ||, and > and
< redirect files. $name expands a variable,
$1 onwards are the script’s arguments, and $(command) inserts
a command’s output. Double quotes keep a value as one word. Comments start with
#.
Control flow closes with reversed words: if and fi,
case and esac, and do and done for
loops. Arrays, [[ ]] tests and many other features exist in Bash, Zsh and
KornShell but not in POSIX sh.
#!/bin/sh
# Report the size of each file named on the command line.
set -eu
for file in "$@"; do
if [ -f "$file" ]; then
size=$(wc -c < "$file")
echo "$file: $size bytes"
fi
done
Links
Software
- GNU Bash – the default shell on most Linux systems (Linux, macOS, Windows through WSL)
- Zsh – the default shell on macOS since 10.15 (macOS, Linux)
- KornShell 93 – maintained version of the KornShell (Linux, macOS, Unix)
- dash – small POSIX shell, used as
/bin/shon Debian and Ubuntu (Linux) - ShellCheck – finds bugs in shell scripts (Windows, macOS, Linux)
Developers
- mvdan/sh – shell parser and the
shfmtformatter (Go) - tree-sitter-bash – Bash grammar for the Tree-sitter parser used by editors
Reference
- Shell Command Language – the POSIX standard for
sh - Bash Reference Manual – the GNU manual
- Zsh documentation – the Zsh manual