Shell Programs
- Two types of syntax: sh/ksh/ash/bash/dash, and csh/tcsh
Arithmetic
- expr 4 + 1 (prints 5)
- seq 1 4 (prints 1 2 3 4)
Command-line Substitutions
- Wildcard file names (e.g. cat *.c → cat file1.c file2.c)
- Backquote: Run a command and embed its output (e.g. i=
expr $i + 1
)
Variables
- Assigning Variables: var=value
- Using Variables: echo “$var” (remember to double quote!)
- PATH: A varaible that specify where to search for binary packages
- Variable Between Strings: “abc${x}abc” puts $x between strings
IO
- read: Space-separated inputs, put the rest in the last variable. (e.g. read a b c)
- Redirect input/output to file: program <stdin >stdout 2>stderr
- Redirect stdout to stderr: program >&2
Redirect stderr to stdout: program 2>&1
- Append to file: program >> stdout_file
- Here Text:
program <<EOF
…stdin content…
EOF
(If <<\EOF is used with backslash, backslash inside content won’t be parsed)
Command-Line Arguments
- $#: Number of arguments passed in
- ${n}: The n-th argument (e.g. $1 is the 1st argument)
- $*: All arguments as a string
(all quotation will be collapsed into one string)