Simple Bash Scripting Tutorial for Beginners

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
19 Min Read

Bash scripting is a niche skill for Linux users and is even useful for DevOps engineers. It provides simple tools like variables, loops, if conditions, and more. You can then group Linux commands to automate your tasks. Let’s start to explore their syntax and usage.

Must Read: 20 Shell Scripting Questions and Answers

In this guide, you’ll explore the essential tools for learning bash scripting.

What is Bash?

Bash, which stands for “Bourne Again SHell,” is a command-line interpreter that acts as a tool for users to interact with the operating system. It parses the commands and executes them in the given sequence.

Bash is known for its flexibility, incorporating features from various shells, and it serves as the default shell for most Linux distributions and macOS.

A Bit of History

Bash was created by Brian Fox in 1989 as a free replacement for the Bourne Shell. Over the years, it has evolved, incorporating features from different shells and becoming a standard tool for scripting and command-line interactions. The Free Software Foundation is now responsible for maintaining it.

Check This: Linux Command Cheat Sheet for Beginners

Bash Scripting Code Structure

A bash script follows a straightforward structure, comprising the following components:

1. Shebang:

  • The shebang is the initial line of your script, specifying the interpreter (Bash, in this case).
   #!/bin/bash

2. Comments:

  • Comments provide human-readable notes in the script, beginning with the # symbol.
   # This is a comment explaining something

3. Variables:

  • Variables store information and are created by assigning values.
   greeting="Hello, World!"

4. User Input:

  • read is used to receive input from the user, making the script interactive.
   echo "What's your name?"
   read username

5. Echo:

  • echo outputs messages to the screen, allowing the script to communicate.
   echo "Hi, $username!"

Syntax for Bash Script Instructions

Bash script instructions are written in a straightforward syntax, employing the following conventions:

1. Bash Scripting Variables

Variables in Bash are used to store and manipulate data. Here’s the syntax for creating and using variables:

variable_name="some_value"

Explanation:

  • Assign a value to a variable using the format variable_name="some_value".
  • The variable name should adhere to Bash variable naming conventions.

Example:

greeting="Hello, World!"

This example initializes a variable named greeting with the value “Hello, World!”.

2. How to Ask for User Input

Receiving input from users makes scripts interactive. Here’s the syntax for capturing user input:

echo "Prompt message"
read variable_name

Explanation:

  • Use echo to display a prompt message.
  • Utilize read to capture input from the user into the specified variable.

Example:

echo "What's your name?"
read username

This example prompts the user for their name and stores the input in the variable username.

3. How to Print a Message Using Echo

Conveying information in the terminal is crucial. Here’s how you use the echo command:

echo "Message to display"

Explanation:

  • Use echo followed by the message enclosed in double quotes to display text.
  • Variables can be included in the message using the format echo "Text $variable_name more text".

Example:

echo "Hi, $username!"

This example echoes a greeting message using the value stored in the username variable.

After understanding these syntaxes, you can use variables, capture user input, and display messages in your Bash scripts.

4. Bash Script Syntax: Arithmetic

Performing arithmetic operations in Bash is essential for numerical computations. Here’s the syntax for arithmetic operations:

result=$((expression))

Explanation:

  • Use $((...)) to enclose the arithmetic expression.
  • Place the arithmetic expression within the double parentheses.

Example:

#!/bin/bash

# Add two numbers and store the result
value1=5
value2=3
sum=$((value1 + value2))

This example computes the sum of value1 and value2, storing the result in the variable sum.

Use the syntax to perform various arithmetic operations in Bash scripts. Adjust the arithmetic expressions based on your specific numerical requirements.

5. Conditionals (if, else, fi)

The if, else, and fi constructs are fundamental for making decisions in Bash scripts. Here’s the syntax breakdown:

if [ condition ]; then
  # Code to execute if the condition is (0) true
else
  # Code to execute if the condition is (1) false
fi

Note: In Bash, the numeric value for true is 0, and for false, it is 1. This convention is commonly used in Unix-like systems, where a command or operation returning 0 indicates success or true, and any other numeric value indicates an error or false.

Explanation:

  • The if statement is initiated with the keyword if, followed by the condition enclosed in square brackets [ ].
  • The then keyword starts the block of code that executes if the condition is (0) true.
  • Place your desired commands or code within the block following then.
  • The else keyword introduces the block of code that executes if the initial condition is false.
  • Insert the desired commands or code within the block following else.
  • The fi keyword signifies the end of the entire conditional block.

Example:

#!/bin/bash

# Check if the length of two strings is equal
string1="Bash"
string2="Scripting"

if [ ${#string1} -eq ${#string2} ]; then
  echo "The length of '$string1' is equal to the length of '$string2'"
else
  echo "The length of '$string1' is not equal to the length of '$string2'"
fi

Explanation:

  • This example compares the lengths of two strings, $string1 and $string2.
  • ${#string} is used to get the length of a string.
  • The -eq operator checks if the lengths are equal.
  • If true, it echoes a message about equal lengths; otherwise, it echoes an alternative message.
  • This demonstrates the versatility of conditional statements beyond numerical comparisons.

You can use strings and numeric values in if conditions.

Let’s now check out the loops in Bash. They allow you to repeat a set of instructions.

6. Bash For Loop

Here’s the syntax breakdown for the for loop:

for variable in list; do
  # Code to execute for each iteration
done

Explanation:

  • The for loop initializes a variable that takes values from a specified list.
  • The do keyword marks the beginning of the code block to be executed for each iteration.
  • Place your desired commands or code within the block following do.
  • The done keyword signifies the end of the for loop.

Example:

for i in {1..5}; do
  echo "Iteration $i"
done

In the above example, the loop prints a message in each round, ranging from 1 to 5.

7. Bash While Loop

The following is the syntax breakdown for the while loop:

while [ condition ]; do
  # Code to execute as long as the condition is (0) true
done

Explanation:

  • The while loop continuously executes the code block until the specified condition is (0) true.
  • The do keyword marks the beginning of the code block to be executed for each iteration.
  • Place your desired commands or code within the block following do.
  • The done keyword signifies the end of the while loop.

Example:

count=1
while [ $count -le 3 ]; do
  echo "Count: $count"
  ((count++))
done

This example demonstrates a while loop that iterates as long as the variable $count is less than or equal to 3. It prints a message for each iteration.

Understanding these loop structures is essential if you have repetition in your tasks. Adjust the loop parameters and code accordingly as per the use case.

Also Read: 20 Bash Script Code Challenges for Beginners with Their Solutions

Advanced Scripting Techniques

Now, it’s time to go through a few advanced techniques. They can give more power to your bash scripting.

1. Define Arrays

Arrays in bash provide a way to store multiple values in a single variable. They are useful when dealing with lists or sets of data. The script example creates an array of fruits. It loops through each element and prints a message in each iteration.

#!/bin/bash
fruits=("Apple" "Orange" "Banana")

for fruit in "${fruits[@]}"; do
  echo "Processing $fruit"
done

In this script, the for loop efficiently processes each fruit in the array, demonstrating the elegance of bash scripting when dealing with structured data.

2. String Manipulation

String manipulation is a key skill for any bash scripter. It is needed to parse substrings and modify them as per the use case.

For example – the following script extracts a substring from a larger string. Check the the commands used for string manipulation.

#!/bin/bash
string="Hello, World!"
substring="${string:0:5}"
echo "Substring: $substring"

Understanding string manipulation allows scriptwriters to parse and manipulate textual information effectively, facilitating various text-processing tasks.

3. File Handling

Effective file handling is fundamental in bash scripting, enabling tasks such as file analysis, processing, and organization. The script below counts the lines in all text files within a specified directory, offering a practical example of file-related operations.

#!/bin/bash
files=$(find . -type f -name "*.txt")

for file in $files; do
  lines=$(wc -l < "$file")
  echo "File: $file, Lines: $lines"
done

This script combines the power of the find command to locate relevant files and the wc command to count lines, providing insight into file-handling techniques.

4. Switching with Case

The case statement in bash is a versatile tool for handling multiple conditions in a more readable manner than nested if-else statements. The following script uses case to determine the file type based on its extension.

#!/bin/bash
file_type=""
read -p "Tell me a filename: " filename

case "$filename" in
  *.txt) file_type="Text File";;
  *.jpg|*.png) file_type="Image File";;
  *) file_type="Some Mystery File";;
esac

echo "$filename is probably a $file_type."

By incorporating case, this script enhances readability and maintainability, especially when dealing with numerous conditions.

5. Handling Mistakes

Robust error handling is crucial in bash scripting to ensure scripts gracefully manage unexpected situations. The provided script sets up a trap to catch errors, calling a custom error-handling function and displaying relevant information.

#!/bin/bash
handle_error() {
  echo "Uh-oh, something went wrong on line $1: $2"
  exit 1
}

trap 'handle_error $LINENO "$BASH_COMMAND"' ERR

# Your superhero script goes here

By utilizing the trap command and a custom error-handling function, this script provides a mechanism to handle errors effectively, aiding in debugging and script reliability.

Bash Scripting Examples

Certainly! Here are 10 beginner-friendly bash scripting examples along with explanations:

1. Hello World

#!/bin/bash
echo "Hello, World!"

This classic example simply prints “Hello, World!” to the terminal. It’s the starting point for many programming languages and serves as a quick way to ensure your bash environment is set up.

2. User Input

#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name! Welcome to bash scripting."

This script prompts the user for their name, reads the input, and then greets them using the entered name.

3. Variables and Arithmetic

#!/bin/bash
num1=5
num2=3

sum=$((num1 + num2))
echo "Sum: $sum"

This example introduces variables and performs basic arithmetic to calculate the sum of two numbers.

4. Conditional Statements

Let’s use the condition to check if the student has scored above the passing marks or not.

#!/bin/bash

# Check if a student passed
score=80
passing=60

if [ $score -ge $passing ]; then
  echo "Congratulations! Student scored $score, passing is $passing."
else
  echo "Unfortunately, student scored $score, below passing ($passing). More effort is needed."
fi

Explanation:

  • This example checks if a student’s score, stored in $score, is equal to or greater than the passing score, stored in $passing.
  • The -ge operator is used for the comparison (greater than or equal to).
  • It echoes a congratulatory message if the score is above the passing score; otherwise, it advises more effort is needed.

So, the above was, a simple bash if-else example comparing the two numeric values.

5. Looping with For

#!/bin/bash
for i in {1..5}; do
  echo "Iteration $i"
done

This loop iterates from 1 to 5, printing a message for each iteration. It’s a basic introduction to for loops in bash.

6. While Loop

#!/bin/bash
count=1

while [ $count -le 3 ]; do
  echo "Count: $count"
  ((count++))
done

This script demonstrates a while loop that iterates as long as the count is less than or equal to 3.

7. Reading from a File

#!/bin/bash
filename="sample.txt"

while read line; do
  echo "Line: $line"
done < "$filename"

Here, the script reads each line from a file (“sample.txt”) and echoes it to the terminal.

8. Command Line Arguments

#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

This script prints the script name and the first two command-line arguments passed when executing the script.

9. Case Statement

#!/bin/bash
read -p "Choose a fruit: " fruit

case $fruit in
  "Apple") echo "You picked an Apple.";;
  "Orange") echo "You picked an Orange.";;
  *) echo "Not sure what you picked.";;
esac

This example demonstrates the use of a case statement to handle different cases based on user input.

10. Basic Function

#!/bin/bash
greet() {
  echo "Hello, $1!"
}

greet "John"

This script defines a simple function (greet) that takes a name as an argument and echoes a greeting. It then calls the function with the name “John.”

These examples cover essential concepts in bash scripting, providing a foundation for beginners to build upon. Experiment with them, modify them as needed, and gradually explore more advanced topics.

More Fun Examples

11. Word Detective

Text processing in bash involves powerful tools like grep for pattern matching. The script below plays the role of a detective, extracting email addresses from a text file using regular expressions.

#!/bin/bash
emails=$(grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" input.txt)
echo "Found some email addresses: $emails"

This script demonstrates how bash can be used for more advanced text processing tasks, providing a glimpse into the world of pattern matching and regular expressions.

12. Internet Explorer

This script ventures into the realm of network automation by pinging a list of servers and reporting their status. It’s like having a friendly chat with each server to check if they’re awake.

#!/bin/bash
servers=("server1" "server2" "server3")

for server in "${servers[@]}"; do
  if ping -c 1 "$server" &> /dev/null; then
    echo "$server is saying 'Hello!'"
  else
    echo "$server is taking a nap."
  fi
done

By integrating the ping command, this script automates the process of checking server availability, demonstrating the practical application of bash in network-related tasks.

What’s Ahead

So far, you have learned the most essential things about bash scripting. However, it’s an open world and you can always expand your bash skills. Apply them in the following two areas and learn as you go.

DevOps Integration

As you advance in bash scripting, explore DevOps practices by integrating your scripts with Continuous Integration/Continuous Deployment (CI/CD) pipelines. This involves automating the testing and deployment of software, enhancing collaboration and efficiency in development workflows.

Microservices Deployment

Dive into the world of microservices orchestration using tools like Kubernetes. Bash scripts can play a crucial role in automating the deployment and scaling of microservices, contributing to the management of complex distributed systems.

Before We Wrap

This simple guide has given you a deeper understanding of basic and advanced bash scripting concepts. From arrays and string manipulation to file handling, control structures, and practical examples, you now have a toolkit to tackle diverse scripting challenges. As you continue your scripting journey, experiment with customization, and stay curious about emerging technologies. Bash scripting is your magic wand – keep casting those spells.

Before you leave, render your support for us to continue. If you like our tutorials, share this post on social media like Facebook/Twitter.

Happy scripting,
TechBeamers.

Share This Article
Leave a Comment
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x