Bash Scripting for Beginners: A Practical Guide

Bash scripting is a skill that can be very useful for anyone who works in cloud-related fields or is preparing for them. Bash scripting allows you to automate tasks, manipulate files, and interact with various systems and services. In this blog, I will introduce you to the basics of bash scripting and show you some practical examples of how to use it.

What is Bash Scripting?

Bash is a command-line interpreter that runs on Linux, Mac OS, and Windows. It is the default shell for most Linux distributions and Mac OS. A shell is a program that takes commands from the user and executes them. You can type commands directly into the shell or write them in a file and run them as a script. A script is a sequence of commands that performs a specific task.

Bash scripting is the process of writing bash scripts using the syntax and features of the bash language. Bash scripting can help you automate repetitive tasks, simplify complex commands, and customize your environment. Bash scripting can also be used to interact with other programs, such as Python, Perl, or Java.

How to Write and Run a Bash Script?

To write a bash script, you need a text editor and a terminal. A text editor is a program that allows you to create and edit text files. A terminal is a program that provides access to the shell. You can use any text editor you like, such as Vim, Nano, or Gedit. You can also use an integrated development environment (IDE) that supports bash scripting, such as Visual Studio Code or Atom.

To create a bash script, follow these steps:

  • Open a text editor and create a new file with the extension .sh. For example, hello.sh

  • Write the following line at the beginning of the file:

#!/bin/bash

This line tells the system that the file is a bash script and where to find the bash interpreter.

  • Write your commands in the file. For example, write the following command to print “Hello World” on the screen:
echo "Hello World"
  • Save the file and close the text editor.

  • Open a terminal and navigate to the directory where you saved the file. For example, if you saved the file in your home directory, type:

cd ~
  • Make the file executable by typing:
chmod +x hello.sh

This command changes the permissions of the file and allows you to run it as a program.

  • Run the file by typing:
./hello.sh

This command executes the file in the current directory.

  • You should see “Hello World” printed on the screen.

Congratulations! You have written and run your first bash script.

Some Basic Bash Commands

Here are some basic bash commands that you can use in your scripts:

  • echo: Prints a message on the screen. For example:
echo "This is a message"
  • read: Reads input from the user and stores it in a variable. For example:
read name
echo "Hello $name"

This script will prompt the user to enter their name and then greet them.

  • if: Executes a block of commands if a condition is true. For example:
read age
if [ $age -ge 18 ]
then
  echo "You are an adult"
else
  echo "You are not an adult"
fi

This script will ask the user to enter their age and then tell them if they are an adult or not.

  • for: Executes a block of commands for each item in a list. For example:
for fruit in apple banana orange
do
  echo "I like $fruit"
done

This script will print “I like apple”, “I like banana”, and “I like orange” on separate lines.

  • while: Executes a block of commands while a condition is true. For example:
count=1
while [ $count -le 10 ]
do
  echo "$count"
  count=$((count+1))
done

This script will print the numbers from 1 to 10 on separate lines.

  • case: Executes a block of commands based on a pattern match. For example:
read animal
case $animal in
  dog)
    echo "Woof"
    ;;
  cat)
    echo "Meow"
    ;;
  *)
    echo "Unknown animal"
    ;;
esac

This script will ask the user to enter an animal and then make an appropriate sound or say “Unknown animal” if it does not match any of the cases.

Some Useful Bash Features

Here are some useful bash features that can enhance your scripts:

  • Variables: Variables are containers that store values. You can assign values to variables using the = operator and access them using the $ prefix. For example:
name="Alice"
echo "Hello $name"

This script will print “Hello Alice” on the screen.

  • Parameters: Parameters are variables that store the arguments passed to a script. You can access them using the $ prefix and a number that indicates their position. For example:
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "The number of parameters is $#"

If you run this script with two arguments, such as:

./script.sh hello world

It will print:

The first parameter is hello
The second parameter is world
The number of parameters is 2
  • Arrays: Arrays are variables that store multiple values. You can assign values to arrays using the = operator and parentheses. You can access them using the $ prefix and brackets. For example:
colors=(red green blue)
echo "The first color is ${colors[0]}"
echo "The second color is ${colors[1]}"
echo "The third color is ${colors[2]}"

This script will print:

The first color is red
The second color is green
The third color is blue
  • Functions: Functions are blocks of commands that can be reused. You can define functions using the function keyword and parentheses. You can call functions using their name and arguments. For example:
function add {
  result=$(( $1 + $2 ))
  echo "The sum is $result"
}

add 3 5
add 10 20

This script will print:

The sum is 8
The sum is 30
  • Arithmetic: You can perform arithmetic operations in bash using the $(( )) syntax. For example:
x=10
y=5
z=$(( x + y ))
echo "The sum of x and y is $z"

This script will print:

The sum of x and y is 15
  • String manipulation: You can manipulate strings in bash using various operators and commands. For example:
name="Alice"
echo "The length of name is ${#name}"
echo "The first letter of name is ${name:0:1}"
echo "The last letter of name is ${name: -1}"
echo "The name in uppercase is ${name^^}"
echo "The name in lowercase is ${name,,}"

This script will print:

The length of name is 5
The first letter of name is A
The last letter of name is e
The name in uppercase is ALICE
The name in lowercase is alice
  • File manipulation: You can manipulate files in bash using various commands and operators. Here are some examples of what can be achieved with bash:
file="test.txt"
if [ -f $file ]
then
  echo "$file exists"
else
  echo "$file does not exist"
fi

if [ -r $file ]
then
  echo "$file is readable"
else
  echo "$file is not readable"
fi

if [ -w $file ]
then
  echo "$file is writable"
else
  echo "$file is not writable"
fi

if [ -e $file ]
then
  echo "$file has size $(stat -c%s $file) bytes"
else
  echo "$file has no size"
fi

cp $file $file.bak # copy file to file.bak
mv $file.bak new.txt # rename file.bak to new.txt
rm new.txt # delete new.txt

cat $file # display the contents of file on the screen
head -n 3 $file # display the first three lines of file on the screen
tail -n 3 $file # display the last three lines of file on the screen

grep "hello" $file # search for the word hello in file and print the matching lines on the screen

sed 's/hello/hi/g' $file # replace all occurrences of hello with hi in file and print the modified contents on the screen

awk '{print $1}' $file # print the first word of each line in file on the screen

Conclusion

Bash scripting is an essential skill for anyone working in or preparing for cloud-related fields. With this guide, you’re well on your way to mastering Bash scripting!

Remember, practice makes perfect. So don’t hesitate to start writing your own scripts and experimenting with what you’ve learned.