Bash - euccas/expmap GitHub Wiki

Bash: Bourne Again SHell

Use Functions

Functions can be declared with or without the function keyword Must declare function first, then use the function

function func () {
    echo "I am a function"
}

Check the number of arguments

  • $# is the number of arguments
  • $0 is the current script with full path
  • $1, $2, …, $9 are the arguments
if [ $# -lt 3 ](/euccas/expmap/wiki/-$#--lt-3-); then
    echo "need 3 arguments!"
    exit 1
fi

Check if a file exists

Use the test file function in Bash: -f file

if [ ! -f $task_file ]; then
    echo "missing file $task_file"
fi

Use sed

sed s/$var1/$var2/g, no need use \ before the $var1, $var2

sed s/$old_project/$new_project/g > $new_file

Use awk

ls -l, the field 9 is the file name

ls -l | awk '{print $9}'

, (( )), and let

  • enables expression computation inside, but no mathematical operators are allowed to use. Can only use -gt, -lt, -eq, etc.
  • (( )) and let allows using mathematical operators
if [ $# -gt 0 ](/euccas/expmap/wiki/-$#--gt-0-); then
fi

if (( $# > 0 )); then
fi

Variable assignment

In Bash, spaces are not allowed around the “=” sign when assigning values to variables

# This is good
var="hello"

# This is error
var = "hello"