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_MESSAGE
with the value “Hello World”.echo $MY_MESSAGE
prints 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_NAME
waits 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.txt
usesawk
to print the first field of each line intest.txt
, assuming fields are separated by a comma and a space.awk -F", " '{ print $0 }' test.txt
prints the entire line.
echo $1
echo $2
echo $1
prints the first argument passed to the script.echo $2
prints 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
fun1
that prints its first argument. fun1 val1 val2
calls the function withval1
as the first argument andval2
as 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=$1
assigns the first argument passed to the script to the variablename
.- The
if
statement checks ifname
is “ali” and prints “ok” if true. - The
elif
checks if1
is equal to1
, which is always true, and prints “ok”. - The
else
block 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.