Skip to main content

Command Palette

Search for a command to run...

Learn Bash Scripting: A Beginner's Guide

Updated
5 min read
Learn Bash Scripting: A Beginner's Guide

Learn Bash Scripting: A Beginner's Guide

Table of Contents

  1. Introduction

  2. Bash Scripting Basics

  3. Variables and User Input

  4. Conditional Statements

  5. Loops and Iterations

  6. Functions

  7. Working with Files

  8. Scripting Best Practices

  9. Conclusion


1. Introduction

Bash scripting is a powerful tool for automating tasks in Linux and macOS environments. It enables users to write programs in the Bash shell to perform system tasks such as file manipulation, process control, and automating repetitive tasks. This guide will walk you through the basics of Bash scripting, starting from the fundamentals and progressing to more advanced topics.


2. Bash Scripting Basics

What is Bash?

Bash (Bourne Again SHell) is the default shell in many Unix-like operating systems. It allows users to write scripts for automating tasks and processing commands directly in the terminal.

Creating Your First Bash Script

To create a Bash script, simply write commands in a text file and save it with a .sh extension. Here’s the basic structure of a script:

#!/bin/bash
# This is a comment
echo "Hello, World!"
  • #!/bin/bash: This line specifies the path to the Bash interpreter.

  • echo "Hello, World!": This command outputs the text "Hello, World!" to the terminal.

Sample Output:

Hello, World!

Making a Script Executable

Before you can run your script, you need to make it executable:

chmod +x script-name.sh

To run the script, use:

./script-name.sh

3. Variables and User Input

Defining Variables

Variables in Bash are used to store data. To assign a value to a variable, use the following syntax:

name="Anup"
echo "Hello, $name"

Sample Output:

Hello, Anup

User Input

To get input from the user, you can use the read command:

echo "Enter your name:"
read name
echo "Hello, $name!"

Sample Output:

Enter your name:
Anup
Hello, Anup!

4. Conditional Statements

Conditional statements allow you to execute code based on certain conditions.

If Statements

The if statement checks if a condition is true. If it is, the code inside the if block is executed.

number=12
if [ $number -gt 10 ]; then
  echo "The number is greater than 10"
fi

Sample Output:

The number is greater than 10

Else and Elif

You can extend an if statement with else and elif (else if) to handle multiple conditions:

number=10
if [ $number -gt 10 ]; then
  echo "The number is greater than 10"
elif [ $number -eq 10 ]; then
  echo "The number is equal to 10"
else
  echo "The number is less than 10"
fi

Sample Output:

The number is equal to 10

Case Statements

The case statement is useful when you have many conditions to check:

choice="apple"
case $choice in
  "apple")
    echo "You selected apple"
    ;;
  "banana")
    echo "You selected banana"
    ;;
  *)
    echo "Invalid selection"
    ;;
esac

Sample Output:

You selected apple

5. Loops and Iterations

Loops are essential for repeating tasks, especially when dealing with lists or conditions.

For Loop

A for loop repeats a command for a specified number of times or through a list:

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

Sample Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

While Loop

A while loop continues to execute as long as a given condition is true:

count=1
while [ $count -le 5 ]; do
  echo "Iteration $count"
  ((count++))
done

Sample Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Until Loop

An until loop is the opposite of a while loop—it runs until the condition becomes true:

count=1
until [ $count -gt 5 ]; do
  echo "Iteration $count"
  ((count++))
done

Sample Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

6. Functions

Functions help organize your code into reusable blocks.

Defining a Function

To define a function, use the following syntax:

greet() {
  echo "Hello, $1"
}
greet "Anup"

Sample Output:

Hello, Anup

Returning Values from Functions

You can also return values from functions using echo and capture them using command substitution:

add() {
  result=$(( $1 + $2 ))
  echo $result
}

sum=$(add 5 7)
echo "The sum is $sum"

Sample Output:

The sum is 12

7. Working with Files

Bash provides several commands for file manipulation. Here are a few common operations:

Creating Files

To create an empty file, use the touch command:

touch newfile.txt

Reading Files

You can read the contents of a file using cat:

cat file.txt

Sample Output:

This is a file for blog.anupkafle.com.np.

Redirecting Output to a File

You can redirect the output of a command to a file using >:

echo "Welcome to blog.anupkafle.com.np" > output.txt

Appending to Files

To append data to a file, use >>:

echo "New line" >> output.txt

8. Scripting Best Practices

Use Comments

Always add comments to explain your code. This makes it easier to understand and maintain.

# This script prints a greeting
echo "Hello, World!"

Sample Output:

Hello, World!

Use Meaningful Variable Names

Choose variable names that describe their purpose. Avoid single-letter variables unless absolutely necessary.

user_name="Anup"

Error Handling

Use proper error handling to ensure your script behaves as expected even when something goes wrong. The exit command can be used to terminate a script with an exit status:

 if [ ! -f "file.txt" ]; then
  echo "File not found!"
  exit 1
fi

Sample Output:

File not found!

Test Your Scripts

Always test your scripts with different inputs and edge cases to ensure they work as expected.


9. Conclusion

Bash scripting is an essential skill for automating tasks and simplifying repetitive operations on Unix-based systems. By understanding the basics such as variables, conditionals, loops, and functions, you can write efficient and powerful scripts to manage your system more effectively.

Remember to always test your scripts, use comments, and follow best practices to ensure your code is clean, readable, and maintainable.

Happy scripting!