This article covers basic and intermediate bash scripting concepts. Each section explains the command prompt instructions to help IT professionals understand and execute these scripts effectively.
#!/bin/bash
This line is called a “shebang” and indicates that the script should be run in the Bash shell.
echo ${name}
The echo command prints the value of the variable name. If name is not set, it will print an empty line.
echo "hello world"
This command prints the string “hello world” to the terminal.
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
echo ${MY_MESSAGE}
MY_MESSAGE="Hello World"sets a variableMY_MESSAGEwith the value “Hello World”.echo $MY_MESSAGEprints the value ofMY_MESSAGE.echo ${MY_MESSAGE}also prints the value ofMY_MESSAGE. Using${}is optional unless the variable name is followed by characters that are part of the string.
read MY_NAME
echo "Hello $MY_NAME - hope you're well."
read MY_NAMEwaits for the user to input a value and assigns it toMY_NAME.echo "Hello $MY_NAME - hope you're well."prints a personalized greeting using the value entered by the user.
expr 1 + 1
The expr command evaluates expressions. Here, it calculates 1 + 1 and outputs 2.
sed -e 's/string_source$/string_target/g' test.txt
The sed command is used for text substitution. This command replaces all occurrences of string_source at the end of lines with string_target in the file test.txt.
awk -F", " '{ print $1 }' test.txt
awk -F", " '{ print $0 }' test.txt
awk -F", " '{ print $1 }' test.txtusesawkto print the first field of each line intest.txt, assuming fields are separated by a comma and a space.awk -F", " '{ print $0 }' test.txtprints the entire line.
echo $1
echo $2
echo $1prints the first argument passed to the script.echo $2prints the second argument passed to the script.
echo $0
This prints the name of the script itself.
echo $?
This prints the exit status of the last executed command. 0 indicates success, and any other number indicates an error.
function fun1() {
echo $1
}
fun1 val1 val2
- This defines a function
fun1that prints its first argument. fun1 val1 val2calls the function withval1as the first argument andval2as the second. It will printval1.
name=$1
if [ $name = "ali" ]; then
echo "ok"
elif [ 1 -eq 1 ]; then
echo "ok"
else
echo "ok"
fi
name=$1assigns the first argument passed to the script to the variablename.- The
ifstatement checks ifnameis “ali” and prints “ok” if true. - The
elifchecks if1is equal to1, which is always true, and prints “ok”. - The
elseblock runs if none of the above conditions are met, printing “ok”.
for i in 1 2 3 4;
do
echo $i
done
This loop iterates over the numbers 1 to 4, printing each number in turn.




