Linux - Bash Script Foundation

type command # command type
help built-in-command

bash path-to-bash-file
bash -n path-to-bash-file # don’t execute, just check syntax
bash -x path-to-bash-file # print each command before execution
sh path-to-bash-file
. path-to-bash-file
path-to-executable-bash-file

# comment

\[Enter] # extend to next line

var=value # set var value (no space)
$var # get var value
${var} # get var value

$(command) # execute command
$((express)) # e.g. math express
declare -i total=$first*$second

“…$var…” # the $var works
‘…$var…’ # the $var doesn’t work
“val1″”val2″ # string add
‘val1”val2′ # string add

$0 # command name
$1 # param 1
$2 # param 2
$? # list command exit code

exit # exit with last $?
exit exit-code

function functionname()
{
    echo $0 # function name
    echo $1 # param 1
    echo $2 # param 2
    …
}

functionname param1 param2 # call function

test # please see `help test`
[ condition ] # 1. double quote (“”) each params; 2. add spaces between params and operator

if [ condition ]; then
    …
elif [ condition ]; then
    …
else
    …
fi

case $var in
  “value1″)
    …
    ;;
  “value2″)
    …
    ;;
  *)
    …
    ;;
esac

while [ condition ]
do
    …
done

until [ condition ]
do
    …
done

for ((i=1; i<=100; i=i+1))
do
    …
done

for var in item1 item2 item3
do
    …
done