Advanced Linux BashShell Scripting for DevOps Engineers.
Table of contents
- 01_05 Bash expansions and substitutions
- 01_06 Brace expansion
- 01_07 Parameter expansion
- 01_08 Command substitution
- 01_09 Arithmetic expansion
- 02_01 Understanding Bash script syntax
- 02_03 Displaying text with 'echo'
- 02_04 Working with variables
- 02_05 Working with numbers
- 02_06 Comparing values with test
- 02_07 Comparing values with extended test
- 02_08 Formatting and styling text output
- 02_09 Formatting output with printf
- 02_10 Working with arrays
- 03_01 Conditional statements with the 'if' keyword
- 03_02 Working with while and until loops
- 03_03 Introducing 'for' loops
- 03_04 Selecting behavior using 'case'
- 03_05 Using functions
- 03_06 Reading and writing text files
- 04_01 Working with arguments
- 04_02 Working with options
- 04_03 Interactive scripts
- 04_04 Getting input from users
- 04_05 Exiting the script
- Conclusion:
Introduction:
Hey there! Welcome to the wacky world of Bash scripting. ๐ Get ready to dive into a series of hilarious examples and explore the wild possibilities of the command line. ๐
01_05 Bash expansions and substitutions
Let's start our bash journey with some mind-blowing expansions and substitutions. Brace yourself! ๐ค
echo ~ ๐
echo ~- ๐ค
01_06 Brace expansion
Now, let's have some fun with brace expansion. Brace yourself for the unexpected! ๐
echo {1..10} ๐ฒ
echo {10..1} ๐ฏ
echo {01..10} ๐
echo {01..100} ๐ต
echo {a..z} ๐
echo {Z..A} ๐
echo {1..30..3} ๐
echo {a..z..2} ๐
touch file_{01..12}{a..d} ๐
echo {cat,dog,fox} ๐ฑ๐ถ๐ฆ
echo {cat,dog,fox}_{1..5} ๐ธ๐ถ๐ฆ
01_07 Parameter expansion
Let's play around with parameter expansion. It's like magic, but with dollar signs! ๐ชโจ
$Proposing="I love You"
echo $Proposing ๐ค
echo ${Proposing:6} ๐โโ๏ธ
echo ${Proposing:6:3} ๐
echo ${Proposing/you/everybody} ๐ค
echo ${Proposing//o/_} ๐ค
echo ${Proposing/o/_} ๐คซ
echo $Proposing:4:3 ๐ฎ
01_08 Command substitution
Time to dive into command substitution. Let's mix commands with our witty remarks! ๐ฌ๐ก
$uname -r ๐ฅ๏ธ
echo "The kernel is $(uname -r)." ๐ป
echo "Result: $(python3 -c 'print("Hello from Python!")' | tr [a-z] [A-Z])" ๐
01_09 Arithmetic expansion
Get your calculators ready because we're about to crunch some numbers! ๐ข๐งฎ
echo $(( 2 + 2 )) ๐ค
echo $(( 4 - 2 )) ๐
echo $(( 4 * 5 )) ๐
echo $(( 4 / 5 )) ๐ฏ
02_01 Understanding Bash script syntax
Now, let's explore the basic syntax of a Bash script. Prepare to have your mind blown! ๐ฅ
nano myscript / vi myscript / vim myscript
#!/usr/bin/env bash
echo "hello" ๐
# This is a comment
echo "there" ๐
chmod +x myscript
./myscript ๐โโ๏ธ
02_03 Displaying text with 'echo'
Let's have a blast with the 'echo' command and make some bold statements! ๐ช๐ข
echo Ashok is sharing knowledge ๐๐
explorewithashok=devops
echo Ashok is sharing knowledge on $explorewithashok ๐๐
echo "The kernel is $(uname -r)" ๐ฅ๏ธ
echo The kernel is $(uname -r) ๐ฅ๏ธ
echo The (kernel) is $(uname -r) ๐ค
echo The \(kernel\) is $(uname -r) ๐
echo 'The kernel is $(uname -r)' ๐ฅ๏ธ
echo "The (kernel) is $(uname -r)" ๐ค
echo "The (kernel) is \$(uname -r)" ๐
echo
echo; echo "More space!"; echo
echo -n "No newline" โโฉ๏ธ
echo -n "Part of "; echo -n "a statement" ๐๐
02_04 Working with variables
Time to unleash the power of variables! Get ready to store some information! ๐ฆ๐ก
#!/bin/bash
Author=Ashok
Age=26
Intererested_in="Devops"
echo $Author ๐
echo $Age ๐
echo $Interested_in ๐
#!/bin/bash
myvar="Hello!"
echo "The value of the myvar variable is: $myvar" ๐ค
myvar="people"
echo "The value of the myvar variable is: $myvar" ๐
declare -r myname="Ashok"
echo "The value of the myname variable is: $myname" ๐ค
myname="Sana"
echo "The value of the myname variable is: $myname" ๐ฎ
declare -l lowerstring="This is some TEXT!"
echo "The value of the lowerstring variable is: $lowerstring" ๐
lowerstring="Let's CHANGE the VALUE!"
echo "The value of the lowerstring variable is: $lowerstring" ๐
declare -u upperstring="This is some TEXT!"
echo "The value of the upperstring variable is: $upperstring" ๐
upperstring="Let's CHANGE the VALUE!"
echo "The value of the upperstring variable is: $upperstring" ๐
declare -p ๐ฆ
env ๐
echo $USER ๐ค
02_05 Working with numbers
Let's have some numerical fun! Prepare for calculations and random surprises! ๐ข๐ฒ
echo $((4+4)) ๐ค
echo $((8-5)) ๐
echo $((2*3)) ๐
echo $((8/4)) ๐ฏ
echo $(( (3+6) - 5 * (5-2) )) ๐ฒ
a=3
((a+=3))
echo $a ๐
((a++))
echo $a ๐
((a++))
echo $a ๐
((a--))
echo $a ๐คช
(($a++))
((a++))
echo $a ๐
a=$a+2
echo $a ๐
declare -i b=3
b=$b+3
echo $b ๐งฎ
echo $((1/3)) ๐ค
declare -i c=1
declare -i d=3
e=$(echo "scale=3; $c/$d" | bc)
echo $e ๐งช
echo $RANDOM ๐ฒ
echo $(( 1 + $RANDOM % 10 )) ๐คช
echo $(( 1 + $RANDOM % 20 )) ๐คช
02_06 Comparing values with test
Time to put our detective hats on and compare values like pros! ๐ฎโโ๏ธ๐
help test โ
[ -d ~ ] ๐
echo $? ๐ค
[ -d /bin/bash ]; echo $? ๐
[ -d /bin ]; echo $? ๐
[ "cat" = "dog" ]; echo $? โ
[ "cat" = "cat" ]; echo $? โ
[ 4 -lt 5 ]; echo $? โ
[ 4 -lt 3 ]; echo $? โ
[ ! 4 -lt 3 ]; echo $? โ
02_07 Comparing values with extended test
Let's level up our comparisons with extended tests! Get ready for some advanced detective work! ๐ฎโโ๏ธ๐ฌ
[[ 4 -lt 3 ]]; echo $? โ
[[ -d ~ && -a /bin/bash ]]; echo $? ๐โ
[[ -d ~ && -a /bin/mash ]]; echo $? ๐โ
[[ -d ~ || -a /bin/bash ]]; echo $? โ
[[ -d /bin/bash ]] && echo ~ is a directory ๐
ls && echo "listed the directory" ๐๏ธ
true && echo "success!" โ
false && echo "success!" โ
[[ "cat" =~ c.* ]]; echo $? โ
[[ "bat" =~ c.* ]]; echo $? โ
02_08 Formatting and styling text output
Time to get fancy with our text output! Let's add some style and flair! ๐ ๐
echo -e "Name\t\tNumber"; echo -e "Scott\t\t123" ๐
echo -e "This text\nbreaks over\nthree lines" ๐
echo -e "\a" ๐
echo -e "Ding\a" ๐
#!/bin/bash
echo -e "\033[33;44mColor Text\033[0m" ๐จ
echo -e "\033[30;42mColor Text\033[0m" ๐จ
echo -e "\033[41;105mColor Text" ๐จ
echo "some text that shouldn't have styling" ๐ฌ
echo -e "\033[0m" ๐จ
echo "some text that shouldn't have styling" ๐ฌ
echo -e "\033[4;31;40mERROR:\033[0m\033[31;40m Something went wrong.\033[0m" ๐จโ
#!/bin/bash
ulinered="\033[4;31;40m"
red="\033[31;40m"
none="\033[0m"
echo -e $ulinered"ERROR:"$none$red" Something went wrong."$none ๐จโ
02_09 Formatting output with printf
Time to become a formatting genius with the mighty printf command! Prepare for elegance! ๐ฉโจ
echo "The results are: $(( 2 + 2 )) and $(( 3 / 1 ))" ๐งฎ
printf "The results are: %d and %d\n" $(( 2 + 2 )) $(( 3 / 1 )) ๐งฎ
#!/bin/bash
echo "----10----| --5--" ๐
echo "Right-aligned text and digits" ๐
printf "%10s: %5d\n" "A Label" 123 "B Label" 456 ๐งฎ
echo "Left-aligned text, right-aligned digits" ๐
printf "%-10s: %5d\n" "A Label" 123 "B Label" 456 ๐
echo "Left-aligned text and digits" ๐
printf "%-10s: %-5d\n" "A Label" 123 "B Label" 456 ๐
echo "Left-aligned text, right-aligned and padded digits" ๐
printf "%-10s: %05d\n" "A Label" 123 "B Label" 456 ๐
echo "----10----| --5--" ๐
printf "%(%Y-%m-%d %H:%M:%S)T\n" 1658179558 โ
date +%s โ
date +%Y-%m-%d\ %H:%M:%S โ
printf "%(%Y-%m-%d %H:%M:%S)T\n" $(date +%s) โ
printf "%(%Y-%m-%d %H:%M:%S)T\n" โ
printf "%(%Y-%m-%d %H:%M:%S)T is %s\n" -1 "the time" โ
02_10 Working with arrays
Let's enter the realm of arrays and unleash the power of list manipulation! ๐๐
declare -a snacks=("apple" "banana" "orange")
echo ${snacks[2]} ๐๐๐
snacks[5]="grapes"
snacks+=("mango")
echo ${snacks[@]} ๐๐ฅญ๐๐๐
for i in {0..6}; do echo "$i: ${snacks[$i]}"; done ๐
declare -A office
office[city]="San Francisco"
office["building name"]="HQ West"
echo ${office["building name"]} is in ${office[city]}" ๐
03_01 Conditional statements with the 'if' keyword
Get ready for some conditional fun! Let's make decisions in our scripts! ๐คโ โ
#!/bin/bash
declare -i a=3
if [[ $a -gt 4 ]]; then
echo "$a is greater than 4!"
else
echo "$a is not greater than 4!"
fi
#!/bin/bash
declare -i a=3
if [[ $a -gt 4 ]]; then
echo "$a is greater than 4!"
elif (( $a > 2 )); then
echo "$a is greater than 2."
else
echo "$a is not greater than 4!"
fi
03_02 Working with while and until loops
Time to create loops and keep things interesting! Let's repeat some actions! ๐๐
#!/bin/bash
echo "While Loop"
declare -i n=0
while (( n < 10 ))
do
echo "n:$n"
(( n++ ))
done
echo -e "\nUntil Loop"
declare -i m=0
until (( m == 10 )); do
echo "m:$m"
(( m++ ))
done
#!/bin/bash
echo "While Loop"
declare -i n=0
while (( n < 10 ))
do
echo "n:$n"
(( n++ ))
done
echo -e "\nUntil Loop"
declare -i m=0
until ((m > m)); do
echo "m:$m"
(( m++ ))
done
03_03 Introducing 'for' loops
Let's dive into the world of 'for' loops! Prepare for repetitive awesomeness! ๐๐
#!/bin/bash
for i in 1 2 3
do
echo $i
done
for i in 1 2 3; do echo $i; done
#!/bin/bash
for i in {1..100}
do
echo $i
done
#!/bin/bash
for (( i=1; i<=100; i++ ))
do
echo $i
done
#!/bin/bash
declare -a fruits=("apple" "banana" "cherry")
for i in ${fruits[@]}
do
echo $i
done
#!/bin/bash
declare -A arr
arr["name"]="scott"
arr["id"]="1234"
for i in "${!arr[@]}"
do
echo $i: "${arr[$i]}"
done
#!/bin/bash
for i in $(ls)
do
echo "Found a file: $i"
done
#!/bin/bash
for i in *
do
echo "Found a file: $i"
done
03_04 Selecting behavior using 'case'
Let's have some fun with the 'case' statement! It's like a menu for our script! ๐๐
#!/bin/bash
animal="dog"
case $animal in
bird) echo "Avian";;
dog|puppy) echo "Canine";;
*) echo "No match!";;
esac
03_05 Using functions
Get ready to define and use functions in our script! Let's make our code modular! ๐งฉ๐ง
#!/bin/bash
greet() {
echo "Hi there."
}
echo "And now, a greeting..."
greet
#!/bin/bash
greet() {
echo "Hi there, $1"
}
echo "And now, a greeting..."
greet Scott
#!/bin/bash
greet() {
echo "Hi there, $1. What a nice $2"
}
echo "And now, a greeting..."
greet Scott Morning
greet Everybody Evening
#!/bin/bash
numberthing() {
declare -i i=1
for f in $@; do
echo "$i: $f"
(( i += 1 ))
done
echo "This counting was brought to you by $FUNCNAME."
}
numberthing "$(ls /)"
echo
numberthing pine birch maple spruce
#!/bin/bash
var1="I'm variable 1"
myfunction() {
var2="I'm variable 2"
local var3="I'm variable 3"
}
myfunction
echo $var1 ๐ฆ
echo $var2 ๐ฆ
echo $var3 ๐ฆ
03_06 Reading and writing text files
Let's read and write text files like wordsmiths! Prepare for textual adventures! ๐๐๏ธ
#!/bin/bash
for i in 1 2 3 4 5
do
echo "This is line $i" > ~/textfile.txt
done
#!/bin/bash
for i in 1 2 3 4 5
do
echo "This is line $i" >> ~/textfile.txt
done
#!/bin/bash
while read f
do
echo "I read a line and it says: $f"
done < ~/textfile.txt
04_01 Working with arguments
Let's dive into the world of command-line arguments! Prepare for some interactive script action! ๐ฅ๐ค
#!/bin/bash
echo "The $0 script got the argument $1" ๐ฏ
#!/bin/bash
echo "The $0 script got the argument $1" ๐ฏ
echo "Argument 2 is $2" ๐ฏ
#!/bin/bash
for i in $@
do
echo $i
done
#!/bin/bash
for i in $@
do
echo $i
done
echo "There were $# arguments." ๐งฎ
04_02 Working with options
Time to level up with command-line options! Let's make our scripts more versatile! โ๏ธ๐
#!/bin/bash
while getopts u:p: option; do
case $option in
u) user=$OPTARG;;
p) pass=$OPTARG;;
esac
done
echo "user: $user / pass: $pass" ๐คซ
#!/bin/bash
while getopts u:p:ab option; do
case $option in
u) user=$OPTARG;;
p) pass=$OPTARG;;
a) echo "got the A flag" ๐ฉ;;
b) echo "got the B flag" ๐ฉ;;
esac
done
echo "user: $user / pass: $pass" ๐คซ
#!/bin/bash
while getopts :u:p:ab option; do
case $option in
u) user=$OPTARG;;
p) pass=$OPTARG;;
a) echo "got the A flag" ๐ฉ;;
b) echo "got the B flag" ๐ฉ;;
\?) echo "Unknown option: -$OPTARG" โ;;
esac
done
echo "user: $user / pass: $pass" ๐คซ
04_03 Interactive scripts
Get ready for interactive script magic! Let's make our scripts communicate with users! ๐ฌโจ
#!/bin/bash
echo "What is your name?"
read name
echo "Nice to meet you, $name" ๐
#!/bin/bash
echo "What is your favorite color?"
read -r color
echo "Ah, $color, an excellent choice!" ๐จ
#!/bin/bash
read -p "What is your favorite animal? " animal
echo "Ah, the $animal, a magnificent creature!" ๐ฆ
#!/bin/bash
read -p "What is your favorite color? " -n 1 -t 5 color
echo -e "\nAh, $color, an excellent choice!" ๐จ
04_04 Getting input from users
Time to get creative with user input! Let's validate and process the information! ๐ต๏ธโโ๏ธ๐ก
#!/bin/bash
read -p "What is your age? " age
if [[ $age =~ ^[0-9]+$ ]]; then
echo "Your age is $age" ๐
else
echo "Invalid age entered!" โ
fi
#!/bin/bash
read -p "Enter a file or directory: " path
if [[ -e $path ]]; then
echo "$path exists!" ๐๏ธ
else
echo "$path does not exist!" โ
fi
#!/bin/bash
while read -p "Enter a number: " number; do
if [[ $number =~ ^[0-9]+$ ]]; then
echo "Valid number entered: $number" ๐งฎ
break
else
echo "Invalid number entered!" โ
fi
done
#!/bin/bash
while read -p "Enter a name: " name; do
if [[ -z $name ]]; then
echo "Name cannot be empty!" โ
else
echo "Hello, $name!" ๐
break
fi
done
04_05 Exiting the script
It's time to wrap things up! Let's gracefully exit our scripts and say our goodbyes! ๐๐
#!/bin/bash
echo "Hello, world!" ๐
exit 0
#!/bin/bash
echo "Hello, world!" ๐
exit 1
#!/bin/bash
echo "Hello, world!" ๐
exit
#!/bin/bash
echo "Hello, world!" ๐
return 0
#!/bin/bash
function exit_script {
echo "Exiting..."
exit
}
echo "Hello, world!" ๐
exit_script
echo "This line will not be executed."
Conclusion:
Congratulations on completing this fun-filled bash scripting adventure! ๐๐ We hope you had a great time exploring the wacky and powerful world of the command line. Remember, the possibilities with bash scripting are endless, so keep experimenting and creating! Happy scripting! ๐๐ป
Hope you like my blog...!
if you like the content follow me on LinkedIn: https://www.linkedin.com/in/ashok-sana
Follow my Whatsapp & telegram community: https://chat.whatsapp.com/BzX1aruZIH645l29LxvgO3
Happy learning......!
Subscribe to my newsletter
Read articles from ASHOK SANA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
ASHOK SANA
ASHOK SANA
Transitioning from agriculture to technology has been a transformative journey. With a strong agricultural background and two years of field experience, I now thrive as an AWS trainer and DevOps Engineer. My agricultural roots instilled efficiency, resource management, and continuous improvement values - all vital in DevOps. As an AWS trainer, I've honed my communication skills and deepened my cloud expertise. I'm committed to staying at the forefront of DevOps, focusing on automation, containerization, and CI/CD pipelines. I bring a unique blend of agricultural insights and tech expertise to drive innovation in organizations' DevOps processes.