Bash Commands Cheat Sheet Red Hat Developer
Bash Commands Cheat Sheet Red Hat Developer
Cheat sheet
Bash commands
A Bash script is a text file that contains programming statements that execute commands that are part of the host
computer’s operating system. Typically system administrators and programmers use Bash scripts to avoid having to
repetitively execute tasks manually in a terminal.
A typical use case for a Bash script is to do set up tasks for a newly provisioned computer. Thus, in addition to being
a tool for system administrators and programmers, a Bash script can also be used by system provisioning software.
(The $ symbol that proceeds commands in the examples represents the command line prompt.)
There are two ways to run a Bash script. The first way is to execute it as a parameter of a direct call to the bash
bash
executable binary, like so:
$ bash myscript
$ chmod +x ./myscript
$ ./myscript
Unlike a binary executable file which knows how to interact with the computer’s operating system directly, a Bash
script, which is always text based, requires another program to run its commands. This other program is called an
interpreter. The interpreter that runs a Bash script is, as the name implies, bash.
bash However, in other cases, a bash script
can be run by another interpreter that’s installed on the host computer. An example of another interpreter is sh sh .
The way a Bash script lets the operating system know which interpreter to use is according to a declaration made at
the first line of the script. This first line declaration is called a script header. It is also called a shebang. A shebang starts
with the characters #!#!
#!/usr/bin/bash
The shebang shown above tells the operating system to use the interpreter located at the filepath /usr/bin/bash
/usr/bin/bash to
execute the lines of code that will follow in the script.
#!/usr/env bash
The shebang #!/usr/env bash tells the operating system to search the computer’s $PATH $PATH to find the bash
bash
interpreter. Thus, any instance of bash
bash can be used as long as the it’s in a location defined by the $PATH
$PATH environment
variable.
The example below shows a Perl script file. Notice that the script header (a.k.a. shebang) declares the file as a Perl
script:
#!/usr/bin/perl
use strict;
use warnings;
Variables
Using variables is a critical factor for programming Bash scripts. The following sections describe various aspects of
working with variables under Bash.
Variable declaration
You declare a variable in a bash script like so VARIABLE_NAME=<value>
VARIABLE_NAME=<value> WHERE <value>
<value> is the value assigned to the
variable. Then, to reference the variable, put the $ symbol before the variable name being referenced, like so:
$
$VARIABLE_NAME.
$VARIABLE_NAME
Example:
#!/usr/bin/env bash
MSG="Hello World"
echo "$MSG " # Hello World
developers.redhat.com redhat-developer @rhdevelopers
BE CAREFUL to make sure there is no space on either side of the == symbol when declaring a variable. The following
will not work: MYVARIABLE
MYVARIABLE = =foo
foo.
MSG="aBcDeFg"
echo ${MSG^^}
#returns ABCDEFG
MSG="aBcDeFg"
echo ${MSG,,}
#returns abcdef
Examples:
The following examples demonstrate various ways to use parameter expansion on Linux variables.
Word replacement
#returns X XXXX 10
developers.redhat.com redhat-developer @rhdevelopers
Replace all numeric characters with the character ZZ but leave alphabetic characters alone
#returns I need ZZ
Extracting substrings
Use the : symbol to get the substring of all the characters after the starting at position 4
Use the : symbol to get the substring that has 7 characters starting at position 4
#returns Rolling
Use the # symbol to get the substring after the characters The
The starting from the left side of the string
Use the % symbol to get the substring before the characters Rolling Stones starting the right side of the string
Rolling Stones
#returns The
Case conversion
Use the ^^ symbol to convert the first character in a string to uppercase.
MSG="aBcDeFg"
echo ${MSG^}
#returns ABcDeFg
developers.redhat.com redhat-developer @rhdevelopers
Use the ^^
^^ symbols to convert the all lowercase characters in a string to uppercase.
MSG="aBcDeFg"
echo ${MSG^^}
#returns ABCDEFG
MSG="TuVwXyZ"
echo ${MSG,}
#returns tuVwXyZ
MSG="TuVwXyZ"
echo ${MSG,,}
#returns tuvwxyz
Collections
The following sections describe how to group data as a collection in a bash script. Bash supports two types of
collections. One type is an array.
array The other type is a map.
map
An array
array is a collection in which elements of the collection are accessed according to a number.
A map
map is a collection in which elements of the collection a key value.
Arrays
Creating an array
The following creates an array with three elements and assigns the array to the variable named my_array.
my_array
my_array+=('Soto')
unset my_array[3]
echo ${my_array[0]}
The following uses an index number to view the data in the third element of the array named my_array.
my_array
echo ${my_array[2]}
echo ${my_array[@]}
echo ${#names[@]} # 3
# Count of names
echo ${#names[@]} # 3
EOF
bash arrays-01.sh
Maps
In Bash, a map is a collection of elements that are organized as key-value pairs. Another way to think of a map is as a
named associative array.
Creating a map
You create a map using the command declare declare-A
-A <map_name>
<map_name> WHERE the option -A
-A indicates that the variable
represents an associative array, which is that same as a map.
Examples:
declare -A score
score[alex]="1"
score[edson]="2"
score[sebi]="3"
score[chris]="4"
echo ${!score[@]}
developers.redhat.com redhat-developer @rhdevelopers
The following example demonstrates calling the value of the element associated with the key edson.
edson
declare -A score
score[alex]="1"
score[edson]="2"
score[sebi]="3"
score[chris]="4"
echo ${!score[@]} # alex edson sebi chris
unset score[chris] # Delete chris entry
echo ${score[@]} # show all the values
echo ${!score[@]} # show all keys
echo ${score[edson]} # show the value of edson: 2
echo ${#score[@]} # show the number of elements in the map: 3
EOF
bash maps-01.sh
Collections
Functions provide a way to group commands in a bash script together under a common name for reuse.
developers.redhat.com redhat-developer @rhdevelopers
The following demonstrates basic function syntax. The function is named printmessages.
printmessages The function uses the echo
command to send two messages to standard output.
printmessages() {
echo "I am message 1"
echo "I am message 2"
}
printmessages() {
echo "I am message 1"
echo "I am message 2"
}
bash function-example-01.sh
Using parameters
Parameters are passed to a function implicitly when added to the execution command of the function.
Parameters are detected in a function by using the $ symbol to call the parameter according the position of the
parameter in the command line.
The following code demonstrates a function that reads the parameter passed as the first argument in the command
line.
chelloworld() {
echo "Hello World from $1"
}
helloworld "Alex"
helloworld() {
echo "Hello World from $1"
}
bash function-example-02.sh
Returns Hello
HelloWorld fromAlex
World from Alex
helloworld() {
echo "Hello World from $1 and $2"
}
bash function-example-03.sh
A function can write data to a variable previous defined in a Bash script. The following bash script demonstrates the
technique.
function set_favorite_food(){
favorite_food=$1
}
favorite_food="apples"
echo favorite_food
set_favorite_food "cheese"
echo favorite_food
favorite_food="apples"
echo $favorite_food
set_favorite_food "cheese"
echo $favorite_food
EOF
bash function-04.sh
Returns
apples
cheese
Conditional statements
if [<statement>]; then
<consequence statement(s)>
fi
An if..then
if..then conditional statement uses the following
if syntax with the else keyword :
if [<statement>]; then
<consequence statement(s)>
else
<consequence statement(s)>
fi
Numeric statements
The following bash script demonstrates using a conditional statement to test numeric values. The code uses the
$RANDOM
$RANDOM function to get a random number. $RANDOM$RANDOM is defined by the operating system and always present. The
expr
expr keyword is the bash command that evaluates an expression. Also, the bash script uses the predefined modulus
(%)
% operator which is available to the script by default from the operating system.
developers.redhat.com redhat-developer @rhdevelopers
mynum=$RANDOM
echo $mynum
if [ $(expr $mynum % 2) == "0" ]; then
echo even
else
echo odd
fi
bash conditional-example-01.sh
String statements
The following bash script demonstrates using a conditional statement to check if a word exists in a string.
EOF
File statements
The following bash script demonstrates using a conditional statement to determine if a file exists.
FILE=/<path/to/filename>
if test -f "$FILE"; then
echo "$FILE exists."
fi
touch newfile.txt
bash conditional-example-03.sh
Loops
developers.redhat.com redhat-developer @rhdevelopers
Looping is a technique that enables Bash scripts to run programming statements and expressions continuously.
Range
The following code demonstrates running a loop over a range according to lower and upper limits.
for i in {1..5}; do
echo "Hello World $i"
done
for i in {1..5}; do
echo "Hello World $i"
done
EOF
bash basic-range-01.sh
Looping collections
for i in "${names[@]}"; do
echo "Hello $i"
done
for i in "${names[@]}"; do
echo "Hello $i"
done
EOF
bash range-names-01.sh
developers.redhat.com redhat-developer @rhdevelopers
declare -A score
score[alex]="1"
score[edson]="2"
score[sebi]="3"
score[chris]="4"
EOF
bash range-keys-01.sh
declare -A score
score[alex]="1"
score[edson]="2"
score[sebi]="3"
score[chris]="4"
EOF
bash value-keys-01.sh
for i in /tmp/*.log; do
echo $i
done
for i in /tmp/*.log; do
echo $i
done
EOF
bash files-01.sh
for i in /var/*; do
echo $(basename "$i")
done
for i in /var/*; do
echo $(basename "$i")
done
EOF
bash files-02.sh
While loop
The following code uses the less then or equal to symbol -le
-le to run a loop until the counter variable x
x reaches the
number 5.5 x
developers.redhat.com redhat-developer @rhdevelopers
x=1;
while [ $x -le 5 ]; do
echo "Hello World"
((x=x+1))
done
Copy and paste the following code to create and run a Bash script that demonstrates a while
while loop.
x=1;
while [ $x -le 5 ]; do
echo "Hello World"
((x=x+1))
done
EOF
bash while-loop-01.sh
Reporting success and error in a Bash script is accomplished using status codes. By convention success is reported by
exiting with the number 00. Any number greater than 00 indicates an error. Also, there is a convention for error
numbers which is explained in the article on Red Hat System Admin Bash command line exit codes demystified.
if [ -z "$1" ]; then
echo "No parameter";
exit 22;
fi
bash status-code-01.sh
echo $?
Returns 22
function echoMessage(){
if [ -z "$1" ]; then
return 22;
fi
}
echoMessage
res=$?
echo The first result of the call to echoMessage is $res
res=$?
echo The second result of the call to echoMessage is $res
EOF
bash status-code-02.sh
Returns