Learn Shell

set PARAMS “set command PARAMS in scripts”:

  • -x “turn on execuation tracking”
  • +x “turn off execuation tracking”
  • — 1 2 3 “set new shell arguments as ‘1 2 3’”
  • -e “exit if command‘s return code isn’t 0”

variables

  • $((x)) “evaluate arithmetic expressions”
  • $(cmd) “exe this cmd and get the output, better”
  • cmd “same as $(cmd)”
  • ${v:-w} “return w if v isn‘t exist or is null. if ’:‘ ignored, just if v isn’t exit”
  • ${v:=w} “set v=w and return if v isn't exist or is null”
  • ${v:?m} “print ‘v:m’ and abort if v isn't exist or is null”
  • ${v:+w} “return null if v isn't exist or is null, else return w. test for the existence of variable”

  • ${v#p}

  • ${v##p}
  • ${v%p}
  • ${v%%p}

  • $0 “command name”

  • $1 ${1} “Nth arguments”
  • $# “number of command arguments (not include command)”
  • shift “shift first argument away”
  • $*,$@ “all arguments”
  • "$*“ ”all arguments as a string, equal to ‘$1 $2 …’ "
  • “$@” “all arguments as individual strings, equal to ‘$1’ ‘$2’…best for another programsl”

  • $? “exit status of previous command”

  • $$ “process ID of shell”
  • $! “last process ID, wait”
  • $- “represent the currently enabled shell options” more in 6.1 table 6-3
  • readonly “make the variable unmodifiable” readonly x=3
  • printf “print to standard output” printf “X is: ‘%s’” $x
  • read “read variables from standard input, separate by $IFS” read x y z
  • PATH=… COMMAND “add or modifity variables only for this COMMAND run”
  • env -i PATH=… COMMAND “not inherited variables only for this COMMAND run”
  • unset PATH “remove variables or functions for runing shell”

if-elif-else-fi

1
2
3
4
5
6
7
8
9
if pipeline ...
then
    ...
elif pipeline ...
then
    ...
else
    ...
fi
  • !: NOT
  • &&: AND
  • ||: NOR
  • ‘:’: do nothing

next codes is same as “if … then …”

1
2
3
4
5
some_command && {
    one command
	a second command
	and a third command
}
  • test: test “$str1” = “$str2” == [ “$str1” = “$str2” ]
  • [[]]: is key word in bash, [[ “$str1” == “$str2” ]] == [ “$str1” = “$str2” ]

see more about test command in 6.2, table 6.6

switch

1
2
3
4
5
6
7
8
9
10
11
case $1 in
-f)
    ...
	;;
-d | --directory)
    ...
	;;
*)
    echo $1: unknown option >&2
	exit 1
esac

loop

1
2
3
4
5
6
7
for i in "$@"; do
    case $i in
	-f) ...
	    ;;
	...
	esac
done

an easy way is use command “getopts”, see in 6.4

while and until

1
2
3
4
5
6
7
while [...]; do
    ...
done

until [...]; do
    ...
done
  • break n

exec/./sh/source

  • sh: fork a new sub-shell and back
  • ./source: run on current shell and back
  • exec: run on current shell and no back