The bash scripting languages syntax is a bit different to C++ or Python. Therefore, this cheat sheet is dedicated for looking up common bash expressions.
Bash variables
Last commands / applications exit code
Conditions
1
2
3
4
5
6
| if [[ ... ]]
then
...
else
...
fi
|
Compact:
1
| if [[ ... ]]; then ...; else ...; fi
|
Negate condition
1
| if [[ ! condition ]] ...
|
Check if file / directory exists
1
2
| if [[ -f <path> ]] # if file exists
if [[ -d <path> ]] # if directory exists
|
Check for string
1
2
| if [[ -z <str> ]] # if length of string = 0
if [[ -n <str> ]] # if length of string != 0
|
Skip first line of command output
1
| <command> | tail -n +2 # number of lines to skip +1
|
stdout / stderr redirection
stderr to stdout
stdout to stderr
stdout and stderr to file
1
| <command> &> output.txt
|
stdout to one file and stderr to another file
1
| <command> > stdout.txt 2> stderr.txt
|
Advanced checks
Check if a port is open
1
| echo -n | telnet <hostname> <port>; echo $?
|
echo -n sends a null character into telnet, closing the connection immediately. when the port is open, telnet returns 0, otherwise 1