Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Bash Scripting for Automation | Automation and Remote Administration
Linux for DevOps Engineer

bookBash Scripting for Automation

A Bash script is a plain text file containing a series of commands that you want the Linux shell to execute in sequence. Bash scripts are powerful tools for automating repetitive tasks, managing system operations, and handling complex workflows. When you write a Bash script, you can combine standard Linux commands, control structures like loops and conditionals, and even interact with files or network resources.

To create a Bash script, start by opening your favorite text editor and writing your commands in the order you want them to run. Always begin your script with the line #!/bin/bash, known as the shebang, which tells the system to use the Bash shell for interpreting the script. Save your file with a .sh extension, such as backup.sh or deploy.sh. Before running the script, make it executable by using the command chmod +x scriptname.sh.

Suppose you want to automate the process of backing up a directory. Your Bash script might include commands to copy files from one location to another, append a timestamp to the backup folder name, and log the results to a file. After saving and making the script executable, you can run it from the terminal by typing ./backup.sh. This approach allows you to repeat complex tasks reliably and efficiently, reducing manual effort and minimizing the chance of errors.

#!/bin/bash
# This is a simple Bash script to greet the user and display the current date and time

echo "Hello, $USER!"  # Prints a greeting with the current user's username
date                 # Displays the current date and time

# End of script

Variables in Bash let you store and reuse data, making scripts flexible. Declare a variable by assigning a value without spaces, e.g., username=devopsadmin. Use $ to access it: echo $username prints "devopsadmin". Variable names can include letters, numbers, and underscores, must start with a letter or underscore, and are case sensitive. For values with spaces, use quotes: greeting="Hello, world" and echo "$greeting from $username" prints "Hello, world from devopsadmin".

Variables can store filenames, user input, or system info. For example, backup_date=$(date +%Y-%m-%d) allows dynamic backup names: cp /etc/hosts "/backup/hosts_$backup_date". You can also assign command outputs: current_user=$(whoami).

Mastering variables helps write scripts that automate real-world DevOps tasks efficiently.

#!/bin/bash
# Define a variable to store your name
USER_NAME="Alice"

# Define a variable for a directory path
BACKUP_DIR="/home/alice/backup"

# Print a welcome message using variables
echo "Hello, $USER_NAME!"

# Print the backup directory path
echo "Your backup directory is set to: $BACKUP_DIR"

# Create the backup directory if it does not exist
if [ ! -d "$BACKUP_DIR" ]; then
  echo "Backup directory does not exist. Creating now."
  mkdir -p "$BACKUP_DIR"
else
  echo "Backup directory already exists."
fi

Understanding Loops in Bash Scripting

Loops in Bash scripting let you repeat a set of commands multiple times. This is essential for automating tasks that require repetition, such as processing files in a directory, monitoring system status, or performing batch operations.

Why Use Loops?

  • Automate repetitive tasks;
  • Process multiple files or data entries efficiently;
  • Reduce manual errors and save time.

Types of Loops in Bash

The two most common loop types in Bash are the for loop and the while loop.

For Loop

A for loop is ideal when you know the number of times you want to repeat a task. You use it to iterate over a list of items, such as filenames or numbers.

Example:

Suppose you want to print the names of all .log files in a directory:

for file in *.log; do
  echo "Processing $file"
done

This loop goes through each file ending in .log and prints its name. You can replace the echo command with any operation you want to perform on each file.

While Loop

A while loop repeats commands as long as a condition is true. This is useful for monitoring or waiting tasks.

Example:

Suppose you want to check if a server is reachable and keep trying every 10 seconds until it responds:

while ! ping -c 1 myserver.com > /dev/null 2>&1; do
  echo "Waiting for server..."
  sleep 10
done
echo "Server is online!"

This loop keeps pinging the server. If the server is not reachable, it prints a message and waits 10 seconds before trying again.

Key Benefits of Loops

  • Handle dynamic lists, such as files or users;
  • Automate monitoring and reporting tasks;
  • Enable efficient resource management and error handling.

Loops are fundamental for any DevOps automation. Mastering them lets you build scripts that scale with your infrastructure and reduce manual intervention.

#!/bin/bash

# Define a list of server names
declare -a servers=("web01" "web02" "db01")

# Loop through each server in the list
for server in "${servers[@]}"
do
  echo "Connecting to $server..."
  # Simulate a command, such as checking uptime
  # ssh $server uptime
  echo "Checked uptime for $server"
done

Conditionals in Bash Scripting

Conditionals in Bash scripting let you control the flow of your script based on whether certain conditions are true or false. The most common way to do this is with the if-else statement. This structure helps you automate tasks that require decision-making, such as checking if a file exists or verifying user input.

The if-else Statement

The basic syntax for an if-else statement in Bash is:

if [ condition ]; then
  # Commands to run if condition is true
else
  # Commands to run if condition is false
fi

You can also use elif (else if) to check multiple conditions:

if [ condition1 ]; then
  # Commands if condition1 is true
elif [ condition2 ]; then
  # Commands if condition2 is true
else
  # Commands if none are true
fi

Real-World Examples

1. Checking if a file exists:

if [ -f "/etc/passwd" ]; then
  echo "The file exists."
else
  echo "The file does not exist."
fi

This script checks if the /etc/passwd file exists. If it does, you see a confirmation message. If not, you get a warning.

2. Verifying user input:

read -p "Enter your name: " name
if [ "$name" = "admin" ]; then
  echo "Welcome, admin."
else
  echo "Access denied."
fi

Here, the script asks for your name. If you enter admin, you are welcomed; otherwise, access is denied.

3. Automating service checks:

service_name="nginx"
if systemctl is-active --quiet $service_name; then
  echo "$service_name is running."
else
  echo "$service_name is not running."
fi

This script checks if the nginx service is running. It prints a message based on the service status.

Use Cases for Conditionals in Automation

  • Checking for required files before starting a deployment;
  • Verifying that services are running before executing dependent tasks;
  • Handling user input and validating configuration options;
  • Responding to errors or unexpected states in scripts.

By using if-else statements in your Bash scripts, you add logic and flexibility to your automation, making your scripts smarter and more reliable.

#!/bin/bash
# Check if a file exists

filename="/etc/passwd"

if [ -f "$filename" ]; then
    # This block runs if the file exists
    echo "File $filename exists."
else
    # This block runs if the file does not exist
    echo "File $filename does not exist."
fi

Automating routine tasks with Bash scripts is a core skill for any DevOps engineer working in a Linux environment.

question mark

Which interpreter is specified by the shebang (#!) at the top of a typical Bash script?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

bookBash Scripting for Automation

Pyyhkäise näyttääksesi valikon

A Bash script is a plain text file containing a series of commands that you want the Linux shell to execute in sequence. Bash scripts are powerful tools for automating repetitive tasks, managing system operations, and handling complex workflows. When you write a Bash script, you can combine standard Linux commands, control structures like loops and conditionals, and even interact with files or network resources.

To create a Bash script, start by opening your favorite text editor and writing your commands in the order you want them to run. Always begin your script with the line #!/bin/bash, known as the shebang, which tells the system to use the Bash shell for interpreting the script. Save your file with a .sh extension, such as backup.sh or deploy.sh. Before running the script, make it executable by using the command chmod +x scriptname.sh.

Suppose you want to automate the process of backing up a directory. Your Bash script might include commands to copy files from one location to another, append a timestamp to the backup folder name, and log the results to a file. After saving and making the script executable, you can run it from the terminal by typing ./backup.sh. This approach allows you to repeat complex tasks reliably and efficiently, reducing manual effort and minimizing the chance of errors.

#!/bin/bash
# This is a simple Bash script to greet the user and display the current date and time

echo "Hello, $USER!"  # Prints a greeting with the current user's username
date                 # Displays the current date and time

# End of script

Variables in Bash let you store and reuse data, making scripts flexible. Declare a variable by assigning a value without spaces, e.g., username=devopsadmin. Use $ to access it: echo $username prints "devopsadmin". Variable names can include letters, numbers, and underscores, must start with a letter or underscore, and are case sensitive. For values with spaces, use quotes: greeting="Hello, world" and echo "$greeting from $username" prints "Hello, world from devopsadmin".

Variables can store filenames, user input, or system info. For example, backup_date=$(date +%Y-%m-%d) allows dynamic backup names: cp /etc/hosts "/backup/hosts_$backup_date". You can also assign command outputs: current_user=$(whoami).

Mastering variables helps write scripts that automate real-world DevOps tasks efficiently.

#!/bin/bash
# Define a variable to store your name
USER_NAME="Alice"

# Define a variable for a directory path
BACKUP_DIR="/home/alice/backup"

# Print a welcome message using variables
echo "Hello, $USER_NAME!"

# Print the backup directory path
echo "Your backup directory is set to: $BACKUP_DIR"

# Create the backup directory if it does not exist
if [ ! -d "$BACKUP_DIR" ]; then
  echo "Backup directory does not exist. Creating now."
  mkdir -p "$BACKUP_DIR"
else
  echo "Backup directory already exists."
fi

Understanding Loops in Bash Scripting

Loops in Bash scripting let you repeat a set of commands multiple times. This is essential for automating tasks that require repetition, such as processing files in a directory, monitoring system status, or performing batch operations.

Why Use Loops?

  • Automate repetitive tasks;
  • Process multiple files or data entries efficiently;
  • Reduce manual errors and save time.

Types of Loops in Bash

The two most common loop types in Bash are the for loop and the while loop.

For Loop

A for loop is ideal when you know the number of times you want to repeat a task. You use it to iterate over a list of items, such as filenames or numbers.

Example:

Suppose you want to print the names of all .log files in a directory:

for file in *.log; do
  echo "Processing $file"
done

This loop goes through each file ending in .log and prints its name. You can replace the echo command with any operation you want to perform on each file.

While Loop

A while loop repeats commands as long as a condition is true. This is useful for monitoring or waiting tasks.

Example:

Suppose you want to check if a server is reachable and keep trying every 10 seconds until it responds:

while ! ping -c 1 myserver.com > /dev/null 2>&1; do
  echo "Waiting for server..."
  sleep 10
done
echo "Server is online!"

This loop keeps pinging the server. If the server is not reachable, it prints a message and waits 10 seconds before trying again.

Key Benefits of Loops

  • Handle dynamic lists, such as files or users;
  • Automate monitoring and reporting tasks;
  • Enable efficient resource management and error handling.

Loops are fundamental for any DevOps automation. Mastering them lets you build scripts that scale with your infrastructure and reduce manual intervention.

#!/bin/bash

# Define a list of server names
declare -a servers=("web01" "web02" "db01")

# Loop through each server in the list
for server in "${servers[@]}"
do
  echo "Connecting to $server..."
  # Simulate a command, such as checking uptime
  # ssh $server uptime
  echo "Checked uptime for $server"
done

Conditionals in Bash Scripting

Conditionals in Bash scripting let you control the flow of your script based on whether certain conditions are true or false. The most common way to do this is with the if-else statement. This structure helps you automate tasks that require decision-making, such as checking if a file exists or verifying user input.

The if-else Statement

The basic syntax for an if-else statement in Bash is:

if [ condition ]; then
  # Commands to run if condition is true
else
  # Commands to run if condition is false
fi

You can also use elif (else if) to check multiple conditions:

if [ condition1 ]; then
  # Commands if condition1 is true
elif [ condition2 ]; then
  # Commands if condition2 is true
else
  # Commands if none are true
fi

Real-World Examples

1. Checking if a file exists:

if [ -f "/etc/passwd" ]; then
  echo "The file exists."
else
  echo "The file does not exist."
fi

This script checks if the /etc/passwd file exists. If it does, you see a confirmation message. If not, you get a warning.

2. Verifying user input:

read -p "Enter your name: " name
if [ "$name" = "admin" ]; then
  echo "Welcome, admin."
else
  echo "Access denied."
fi

Here, the script asks for your name. If you enter admin, you are welcomed; otherwise, access is denied.

3. Automating service checks:

service_name="nginx"
if systemctl is-active --quiet $service_name; then
  echo "$service_name is running."
else
  echo "$service_name is not running."
fi

This script checks if the nginx service is running. It prints a message based on the service status.

Use Cases for Conditionals in Automation

  • Checking for required files before starting a deployment;
  • Verifying that services are running before executing dependent tasks;
  • Handling user input and validating configuration options;
  • Responding to errors or unexpected states in scripts.

By using if-else statements in your Bash scripts, you add logic and flexibility to your automation, making your scripts smarter and more reliable.

#!/bin/bash
# Check if a file exists

filename="/etc/passwd"

if [ -f "$filename" ]; then
    # This block runs if the file exists
    echo "File $filename exists."
else
    # This block runs if the file does not exist
    echo "File $filename does not exist."
fi

Automating routine tasks with Bash scripts is a core skill for any DevOps engineer working in a Linux environment.

question mark

Which interpreter is specified by the shebang (#!) at the top of a typical Bash script?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3
some-alt