Test Builtin
test expression [ expression ] Note: Since all expressions and operators used by test are treated as command arguments by the shell, characters that have special meaning to bash, such as <,>,(, and ), must be quoted or escaped.
test expression [ expression ] Note: Since all expressions and operators used by test are treated as command arguments by the shell, characters that have special meaning to bash, such as <,>,(, and ), must be quoted or escaped.
Tilde Expansion # Prefix Value ~ $HOME ~user Home dir of user ~+ $PWD ~- $OLDPWD ~N dirs +N ~+N dirs +N ~-N dirs -N References # Tilde Expansion - gnu.org
Break large, complex tasks into a series of small, simple tasks. Use functions Test frequently Use stubs; empty functions Put feedback in functions/script for programmer
trap argument signal [signal…] #!/bin/bash # trap-demo: simple signal handling demo trap "echo 'I am ignoring you.'" SIGINT SIGTERM for i in {1..5}; do echo "Iteration $iof 5" sleep 5 done #!/bin/bash # trap-demo2: simple signal handling demo exit_on_signal_SIGINT () { echo "Script interrupted." 2>&1 exit 0 } exit_on_signal_SIGTERM () { echo "Script terminated." 2>&1 exit 0 } trap exit_on_signal_SIGINT SIGINT trap exit_on_signal_SIGTERM SIGTERM for i in {1..5}; do echo "Iteration $iof 5" sleep 5 done
Use syntax highlighting to spot syntax errors Missing or unexpected tokens Don’t forget ; and to close if and loops. Quote expansions in test to avoid errors [ "$number" = 1 ] ALWAYS enclose variables and command substitutions in double quotes unless word splitting is needed. Logical Errors Incorrect conditional expressions “Off by one” errors. counters in loops Unanticipated situations Program encounters data or situations unforeseen. ...
Does the opposite of while and continues until true Example #!/bin/bash # until-count: display a series of numbers count=1 until [[ "$count" -gt 5 ]]; do echo "$count" count=$((count + 1)) done echo "Finished."
${!prefix*} ${!prefix@} Both return existing variables with the names beginning with prefix.
key=var echo $key var Variables aren’t assigned until the shell encounters them. Naming Rules # Variable names may consist of [:alnum:_]+ The first character of a variable name must be either a letter or _ Spaces and punctuation not allowed Common convention is for CONSTANTS to be uppercase and variables lowercase. Assigning Values # Treats all variables as strings. No spaces in assignment. key= "var" won’t work, for example. ...
while commands; do commands; done Like if while evaluates the exit status of a list of commands while continues until either a break or the commands evaluate to false Example: #!/bin/bash # while-count: display a series of numbers count=1 while [[ "$count" -le 5 ]]; do echo "$count" count=$((count + 1)) done echo "Finished."