5 Bash Script Examples Every Linux User Should Know


7 min read 10-11-2024
5 Bash Script Examples Every Linux User Should Know

The Linux command-line interface (CLI) is a powerful tool that can be used to manage and automate tasks. Bash scripting is a crucial aspect of leveraging the Linux CLI to streamline processes and boost productivity. By crafting simple scripts, you can automate repetitive tasks, manage system resources, and accomplish complex actions with ease. This article delves into five fundamental Bash script examples that every Linux user should be familiar with. Each example is meticulously explained, emphasizing the key concepts involved and highlighting the practical applications. Let's explore the world of Bash scripting, one example at a time.

Example 1: Navigating and Listing Files

This script utilizes basic commands to navigate directories and list files, showcasing how to interact with the file system in a script.

#!/bin/bash

# Navigate to the home directory
cd /home/user

# List all files and directories in the current directory
ls -l

# Create a new directory
mkdir new_directory

# Change into the newly created directory
cd new_directory

# Create a new file
touch new_file.txt

# List the files in the current directory again
ls -l

# Move back to the home directory
cd ..

# Print a message to the console
echo "Script execution complete!"

Explanation:

  • #!/bin/bash: This line is called a shebang and tells the system to execute the script using the Bash interpreter.
  • cd /home/user: This command changes the working directory to /home/user.
  • ls -l: This command lists the files and directories in the current directory with detailed information, including permissions, owner, size, and modification date.
  • mkdir new_directory: Creates a new directory named "new_directory" in the current directory.
  • cd new_directory: Changes the working directory to the newly created "new_directory".
  • touch new_file.txt: Creates a new empty file named "new_file.txt" in the current directory.
  • echo "Script execution complete!": Prints a message to the console indicating that the script has finished executing.

Practical Applications:

  • File Organization: Create a script to automatically organize files by type, moving them into designated directories.
  • System Maintenance: Automate the process of cleaning up temporary files and outdated logs.
  • Backup Script: Create a script to back up essential files to a designated location.

Example 2: Conditional Statements

This script demonstrates how to use conditional statements to control the flow of execution based on certain criteria.

#!/bin/bash

# Get the current date
today=$(date +%Y-%m-%d)

# Compare the date with a specific date
if [ "$today" == "2023-12-25" ]; then
  echo "Merry Christmas!"
elif [ "$today" == "2024-01-01" ]; then
  echo "Happy New Year!"
else
  echo "Have a nice day!"
fi

Explanation:

  • today=$(date +%Y-%m-%d): This command captures the current date in the "YYYY-MM-DD" format and stores it in the variable today.
  • if [ "$today" == "2023-12-25" ]; then: This condition checks if the current date is December 25th, 2023.
  • echo "Merry Christmas!": If the date matches, this message is printed to the console.
  • elif [ "$today" == "2024-01-01" ]; then: If the first condition is not met, this condition checks for January 1st, 2024.
  • echo "Happy New Year!": If the date matches, this message is printed to the console.
  • else: This block is executed if neither of the previous conditions is met.
  • echo "Have a nice day!": This message is printed to the console if neither condition is true.
  • fi: This line closes the if statement.

Practical Applications:

  • System Monitoring: Check if a particular service is running and send an alert if it's not.
  • User Management: Check for new user accounts and assign appropriate permissions.
  • File Processing: Process files based on their date of creation or modification.

Example 3: Loops and Iteration

This script showcases the use of loops to repeat a set of commands multiple times, allowing for iterative tasks.

#!/bin/bash

# Create a loop that iterates five times
for i in {1..5}; do
  # Print the current iteration number
  echo "Iteration: $i"
done

# Create a loop that iterates over a list of files
for file in *; do
  # Print the filename
  echo "File: $file"
done

# Create a loop that iterates until a specific condition is met
count=0
while [ $count -lt 10 ]; do
  echo "Count: $count"
  count=$((count + 1))
done

Explanation:

  • for i in {1..5}; do: This loop iterates from 1 to 5, executing the commands inside the loop body for each iteration.
  • echo "Iteration: $i": Prints the current iteration number to the console.
  • done: This line closes the for loop.
  • for file in *; do: This loop iterates over all files in the current directory, executing the commands inside the loop body for each file.
  • echo "File: $file": Prints the filename to the console.
  • count=0: Initializes the variable count to 0.
  • while [ $count -lt 10 ]; do: This loop continues executing as long as the variable count is less than 10.
  • echo "Count: $count": Prints the current value of count to the console.
  • count=$((count + 1)): Increments the count variable by 1 in each iteration.

Practical Applications:

  • File Processing: Process multiple files with a single script, performing actions like renaming, copying, or deleting.
  • System Monitoring: Continuously check for system resource usage and log the results.
  • Automated Testing: Run a series of tests and report the results.

Example 4: Input and User Interaction

This script demonstrates how to interact with users, taking input and responding accordingly.

#!/bin/bash

# Prompt the user for their name
read -p "Enter your name: " name

# Welcome the user
echo "Hello, $name! Welcome to the Bash scripting world."

# Ask the user for their favorite color
read -p "What is your favorite color? " color

# Respond based on the user's input
if [ "$color" == "blue" ]; then
  echo "You have excellent taste!"
else
  echo "That's a great color too!"
fi

Explanation:

  • read -p "Enter your name: " name: This command prompts the user to enter their name and stores the input in the variable name.
  • echo "Hello, $name! Welcome to the Bash scripting world.": This command prints a welcome message to the console, incorporating the user's name.
  • read -p "What is your favorite color? " color: This command prompts the user for their favorite color and stores the input in the variable color.
  • if [ "$color" == "blue" ]; then: This condition checks if the user's favorite color is blue.
  • echo "You have excellent taste!": If the color is blue, this message is printed to the console.
  • else: This block is executed if the color is not blue.
  • echo "That's a great color too!": This message is printed to the console if the color is not blue.

Practical Applications:

  • Interactive Menus: Create interactive menus with choices that allow users to select different options.
  • Simple Games: Build rudimentary text-based games where users can interact with the script.
  • Data Collection: Collect user data and store it in files for later processing.

Example 5: Working with Functions

This script demonstrates the use of functions to organize code into reusable blocks, enhancing modularity and readability.

#!/bin/bash

# Define a function to calculate the sum of two numbers
sum_function () {
  # Extract the arguments passed to the function
  num1=$1
  num2=$2

  # Calculate the sum
  sum=$((num1 + num2))

  # Return the sum
  return $sum
}

# Define a function to greet the user
greet_user () {
  echo "Hello, user! Welcome to the function world!"
}

# Call the greet_user function
greet_user

# Call the sum_function and store the result
sum_function 5 10
sum=$?

# Print the sum
echo "The sum of 5 and 10 is: $sum"

Explanation:

  • sum_function () { ... }: This defines a function called sum_function that takes two arguments.
  • num1=$1: This line extracts the first argument and stores it in the variable num1.
  • num2=$2: This line extracts the second argument and stores it in the variable num2.
  • sum=$((num1 + num2)): This line calculates the sum of the two arguments and stores it in the variable sum.
  • return $sum: This line returns the value of sum to the calling script.
  • greet_user () { ... }: Defines a function called greet_user that prints a welcome message.
  • greet_user: Calls the greet_user function.
  • sum_function 5 10: Calls the sum_function with arguments 5 and 10.
  • sum=$?: Stores the return value of the sum_function (which is the calculated sum) in the variable sum.
  • echo "The sum of 5 and 10 is: $sum": Prints the result of the sum_function to the console.

Practical Applications:

  • Complex Tasks: Break down complex tasks into smaller, manageable functions, making the code more modular and easier to understand.
  • Reusable Code: Create functions that can be reused across multiple scripts, reducing code duplication and improving efficiency.
  • Error Handling: Create specific functions to handle different error scenarios, ensuring robust and reliable scripts.

Conclusion

These five Bash script examples provide a solid foundation for your journey into the world of Bash scripting. Remember, the key is to understand the basic concepts, such as variables, operators, control flow, and functions. With practice and exploration, you can leverage the power of Bash scripting to automate tasks, streamline your workflow, and unlock the full potential of your Linux system.

FAQs

1. What is the difference between a Bash script and a shell script?

  • Bash script: A script written specifically for the Bash shell.
  • Shell script: A script that can be executed by any shell, but Bash is the most common.

2. Can I run Bash scripts on Windows?

  • Yes, but you'll need a Bash environment like Git Bash or Cygwin.

3. How can I debug a Bash script?

  • Use the echo command to print variables and values to the console for debugging.
  • Use the set -x command to enable verbose execution, showing each line of code as it's executed.

4. Where can I find more Bash script examples?

  • There are numerous online resources, including tutorials, articles, and code repositories. Websites like GitHub and Stack Overflow are great places to start.

5. What are some common Bash scripting tools?

  • grep: Searches for patterns in text files.
  • sed: Edits text files.
  • awk: Processes data from text files.
  • curl: Downloads data from web servers.
  • wget: Downloads files from the internet.