Skip to content

Shell scripting

Austin Kong edited this page Jul 26, 2016 · 2 revisions

Shell scripting

Variables

Set

varname=value

Use

echo ${varname}

Naming rule [A-Za-z][A-Za-z0-9_]*

Special variables

$# # Number of command-line arguments
$* # All of the positional parameters, seen as a single word. Must be quoted
$@ # Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word. Must be quoted
$! # PID of last job run in background
$- # Flags passed to script
$? # Exit status of a command, function, or the script itself
$$ # PID

Conditional statements

if [ comparison ]; then
    do stuff
elif [ comparison ]; then
    do other stuff
else
    do things
fi

Loops

for varname in list ; do
    body
done

while [comparison ]; do
    while-true statements
done

until[comparison ]; do
    while-false statements
done

Functions

funcname () {
    body
}