Bash Shell Cheat Sheet
Bash Shell Cheat Sheet
developers.redhat.com | @RHDevelopers
Bash is a version of the classic Unix shell with many enhancements. Bash is the default shell installed on GNU/Linux distributions and many other Unix-style
systems. This cheat sheet covers some useful concepts in Bash scripting.
If a command in the examples produces output, the output is shown on the same line, separated from the command by a hash or pound sign (#).
#!/usr/bin/env bash }
echo "Hello World"
msg=$(helloworld)
echo $msg
VARIABLES & STRINGS
#!/usr/bin/env bash
MSG="Hello World" COLLECTIONS
echo "$MSG Alex" # Hello World Alex
echo '$MSG Alex' # $MSG Alex Arrays
FUNCTIONS
CONDITIONALS
helloworld() {
echo "Number of arguments $#" # 2 if [[ $a -gt 4 ]]; then
echo "Hello World $1 from $2" # Hello World Alex from Bash echo "$a is greater than 4"
} elif [[ $a -lt 4 ]]; then
helloworld "Alex" "Bash" echo "$a less than 4"
else
Returning Values echo "$a is equal 4"
fi
helloworld () {
return 46 Numeric Conditions
}
helloworld [[ NUM -eq NUM ]] Equal
echo $? # 46
[[ NUM -ne NUM ]] Not equal
Bash can return only a status code. To return a string, use command [[ NUM -lt NUM ]] Less than
substitution: [[ NUM -le NUM
helloworld() { Less than or equal to
a]]
echo 'My return string!'
[[ NUM -gt NUM ]] [[ NUM -ge NUM ]] Greater than or equal to
CHEAT SHEET
developers.redhat.com | @RHDevelopers
LOOPS DIR="${0%/*}"
for ((i = 0 ; i < 10 ; i++)); do
echo "Hello World $i" Reading CLI Arguments:
done
echo "$1 $2"
Range #######
execute.sh "Hello" "Alex"
for i in {1..5}; do # Hello Alex
echo "Hello World $i"
done
Print Output
Subshell
A shell script can launch subshells. These subshells let the script do
parallel processing, in e ect executing multiple subtasks simultaneously.
(
# Inside parentheses, and therefore a subshell . . .
while [ 1 ] # Endless loop.
do
echo "Subshell"
done
)