Bash Scripting Basics

Bash scripting is a powerful tool for automating tasks, streamlining workflows, and managing Linux systems efficiently. Whether you're a system administrator, developer, or just working in a Linux environment, learning the basics of Bash scripting can greatly enhance your productivity and allow you to perform complex operations with ease. This guide introduces the fundamentals of Bash scripting, providing the building blocks you need to create your own scripts.

What is Bash?

Bash (Bourne Again SHell) is a command-line interpreter and scripting language widely used on Linux systems. It allows users to interact with the operating system, execute commands, and write scripts to automate tasks. Bash scripts are text files containing a series of commands that are executed sequentially by the Bash shell.

Creating Your First Bash Script

1. Start with a Shebang

Every Bash script begins with a shebang (#!) followed by the path to the Bash interpreter. This line tells the system which interpreter to use to execute the script.

#!/bin/bash

This should be the first line in your script file.

2. Write Your Commands

After the shebang, you can start adding commands. Each command is written on a new line and is executed in order.

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

3. Save and Run Your Script

Save the script with a .sh extension, for example, hello_world.sh.

To run the script:

  1. Make it executable:

    chmod +x hello_world.sh
  2. Execute the script:

    ./hello_world.sh

You should see the output Hello, World! printed to your terminal.

Variables in Bash

Variables in Bash allow you to store and manipulate data. You can assign values to variables and reference them later in your script.

Defining Variables

#!/bin/bash
greeting="Hello, World!"
echo $greeting
  • No Spaces: Ensure there are no spaces around the = when assigning a value to a variable.
  • Referencing Variables: Use the $ symbol before the variable name to reference its value.

Using Variables

Variables can hold strings, numbers, or the output of commands.

#!/bin/bash
name="Cycle.io"
echo "Welcome to $name!"

You can also perform arithmetic operations using variables:

#!/bin/bash
a=5
b=10
sum=$((a + b))
echo "The sum of $a and $b is $sum"

Conditional Statements

Conditional statements allow you to make decisions in your script based on certain conditions.

if Statements

The if statement checks a condition and executes commands if the condition is true.

#!/bin/bash
if [ $1 -gt 10 ]
then
    echo "The number is greater than 10"
else
    echo "The number is 10 or less"
fi
  • Comparison Operators:
    • -eq: Equal to
    • -ne: Not equal to
    • -gt: Greater than
    • -lt: Less than
    • -ge: Greater than or equal to
    • -le: Less than or equal to

elif and else

You can chain multiple conditions using elif and provide a fallback using else.

#!/bin/bash
if [ $1 -gt 10 ]
then
    echo "The number is greater than 10"
elif [ $1 -eq 10 ]
then
    echo "The number is exactly 10"
else
    echo "The number is less than 10"
fi

Loops in Bash

Loops allow you to repeat a set of commands multiple times, which is useful for automating repetitive tasks.

for Loops

A for loop iterates over a list of items, executing commands for each item.

#!/bin/bash
for i in 1 2 3 4 5
do
    echo "Iteration $i"
done

You can also use a range of numbers:

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

while Loops

A while loop continues to execute as long as the specified condition is true.

#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
    echo "Counter: $counter"
    ((counter++))
done

until Loops

An until loop is similar to a while loop, but it runs until the condition becomes true.

#!/bin/bash
counter=1
until [ $counter -gt 5 ]
do
    echo "Counter: $counter"
    ((counter++))
done

Functions in Bash

Functions in Bash allow you to group commands into reusable blocks, making your scripts more modular and easier to maintain.

Defining and Calling Functions

#!/bin/bash
greet() {
    echo "Hello, $1!"
}
 
greet "Cycle.io"
  • Parameters: $1, $2, etc., represent positional parameters passed to the function.
  • Calling Functions: Simply use the function name followed by any arguments.

Returning Values

Functions can return values using the return command or by echoing a value that can be captured.

#!/bin/bash
add() {
    echo $(( $1 + $2 ))
}
 
result=$(add 5 10)
echo "The sum is $result"

Script Arguments

Bash scripts can accept arguments from the command line, allowing you to pass data to your script.

Accessing Arguments

#!/bin/bash
echo "The first argument is $1"
echo "The second argument is $2"
  • $0: The script name.
  • $1, $2, etc.: Positional parameters representing the arguments.
  • $#: The number of arguments passed.
  • $@: All arguments as separate words.

Read more about bash scripting in the advanced bash scripting guide or bash scripting best practices guide.