You are on page 1of 3

CHEAT SHEET

developers.redhat.com | @RHDevelopers

Bash Shell Scripting

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 (#).

BASH SCRIPT HEADER

#!/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

String Manipulation names=('Alex' 'Ada' 'Alexandra')


names+=('Soto') # Appends element
MSG="hello world" unset names[3] # Removes element
# Replace
echo ${MSG/w/W} # hello World echo ${names[0]} # Alex
echo ${MSG//[a-zA-Z]/X} # XXXXX XXXXX echo ${names[@]} # Alex Ada Alexandra
# Substring echo ${#names[@]} # 3
echo ${MSG:0:5} # hello
echo ${MSG%world} # hello
echo ${MSG#hello} # world Maps
# Uppercase
echo ${MSG^} # Hello world declare -a score
echo ${MSG^^} # HELLO WORLD score[alex]="1"
MSG="HELLO WORLD" score[edson]="2"
echo ${MSG,} # hELLO WORLD score[sebi]="3"
echo ${MSG,,} # hello world unset score[alex] # Delete alex entry
# Alternative
echo ${MSG:-val} # HELLO WORLD echo ${!score[@]} # alex edson sebi
echo ${FOO:-val} # val echo ${score[@]} # 2 1 3
echo ${#score[@]} # 3

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"

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

Greater than done

cat /tmp/hello.txt | while read line; do


String Conditions echo $line
done
[[ STRING
== STRING Equal
]] While
[[ STRING !=
Not Equal x=1;
STRING ]]
while [ $x -le 5 ]; do
[[ -z STRING
Empty string echo "Hello World"
]]
done
[[ -n STRING
Not empty string
]]
[[ STRING
EXECUTING COMMANDS
=~ STRING Regular expression match
]] Execute a command and check the exit status:
cat /tmp/hello.txt

File Conditions if [ $? -eq 0 ]


then
[[ -f FILE ]] Is a le echo "OK"
else
[[ -d FILE ]] Is a directory
echo "KO"
[[ -e FILE ]] Exists fi
[[ -r -w -x
Is readable, Writable, executable To get the output of a command, surround the call with "\`" character:
FILE ]]
lines=(`cat "/tmp/hello.txt"`)
[[ -h FILE ]] Is symbolic link lines="$(cat "/tmp/hello.txt)"
Boolean conditions:
a|[[ ! EXPR ]] |Not
a|[[ BOOL && BOOL ]] |And USEFUL SNIPPETS
a|[[ BOOL || BOOL ]] |OR
Getting the Script Directory

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

Collections printf "\n\n######## Deploying ########\n"

Print all elements from a plain array:


for i in "${names[@]}"; do
Read Input
echo "Hello $i"
done
echo -n "Enter name: "
Print keys and values of all elements from a key/value array: read ans
for key in "${!score[@]}"; do echo $ans
echo $key
done

for val in "${score[@]}"; do


Create File with Content
echo $val
done echo "
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
Files
- resources:
- secrets
for i in /tmp/*.txt; do providers:
echo $i
CHEAT SHEET
developers.redhat.com | @RHDevelopers

- aescbc: ps -ef | grep execute.sh


keys: 501 4286 641 0 11:17AM ttys007 0:00.00 /bin/bash ./execute.sh
- name: key1 501 4287 4286 0 11:17AM ttys007 0:07.67 /bin/bash ./execute.sh
secret: b6sjdRWAPhtacXo8mO1cfgVYWXzwuls3T3NQOo4TBhk=
- identity: {} Two processes are started. The rst one (4286) as parent of the second.
" | tee /var/lib/minikube/certs/encryptionconfig.yaml

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
)

Run the following command in a new terminal:

You might also like