Bash - cheat sheet
Contents
Arguments
variable | description |
---|---|
$0 |
name of the script |
$1 |
first argument |
$2 |
second argument |
$<n> |
<nth> argument, where n > 0 |
$@ |
all arguments as one string |
$# |
count of arguments |
Example
#!/bin/bash
echo script started with $# args: $@
for arg in "$@"; do
echo "$arg"
done
# $ ./script.sh --config=test --verbose 1 2
# script started with 4 args: --config=test --verbose 1 2
# --config=test
# --verbose
# 1
# 2
Conditionals
if [[ <CONDITION> ]]; then
...
elif [[ <CONDITION> ]]; then
...
else
...
fi
condition | description |
---|---|
"$VAR" == "STRING" |
compare content of env var with string |
-z "$VAR" |
test if string length is zero |
-n "$VAR" |
test if string length is not zero |
-f "$VAR" |
test if regular file exist |
Colors
Print the rainbow: for (( i = 0; i < 39; i++ )); do echo -ne "\033[0;"$i"m Normal: (0;$i); \033[1;"$i"m Light: (1;$i)\t\t\t\t\t"; done
1
Prefix \033
is preferrable over \x1b
and \e
, as its supported on more platforms.
- Inspired from SO