Advanced Linux BashShell Scripting for DevOps Engineers.

ยท

11 min read

Advanced Linux BashShell Scripting for DevOps Engineers.

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

https://t.me/ExplorewithAshok

Happy learning......!

Did you find this article valuable?

Support Ashoksana by becoming a sponsor. Any amount is appreciated!

ย