Introduction to Bash Scripting

Bash scripting is a powerful tool for automating tasks on Unix-like operating systems. Bash, which stands for Bourne Again SHell, is not only the default command-line shell for Linux but also a scripting language in its own right. By writing bash scripts, users can automate repetitive tasks, streamline their workflow, and even manage systems and applications efficiently.

Advertisement

One of the main advantages of bash scripting is its simplicity and ease of use. With just a basic understanding of command-line operations and a few scripting fundamentals, users can create scripts that perform complex operations, making it an ideal starting point for those looking to delve into the world of programming and system administration.

Bash scripts are essentially a series of commands that are executed sequentially by the bash shell. These scripts can include loops, conditionals, and user-defined functions, allowing for sophisticated control structures and the ability to handle a wide range of automation tasks. Whether it’s automating backups, deploying software, or monitoring system health, bash scripting offers a versatile and powerful solution.

Setting Up Your Environment

Before you can start bash scripting, you need to set up your environment. This involves ensuring you have access to a Unix-like operating system, such as Linux or macOS, and a text editor to write your scripts.

  • Operating System: Most Linux distributions come with the bash shell installed by default. You can check if bash is available on your system by typing echo $SHELL in your terminal. If bash is installed, this command will print the path to the bash executable. On macOS, bash is also commonly available, though you may want to update to the latest version using a package manager like Homebrew.
  • Text Editor: Any text editor can be used to write bash scripts, but some offer features like syntax highlighting and auto-completion that can make scripting easier. Popular choices include Vim, Emacs, and Visual Studio Code. Choose an editor that you are comfortable with, as you’ll be spending a lot of time writing and debugging your scripts.
  • Hello World Script: Once your environment is set up, you’re ready to write your first bash script. This will typically involve using your text editor to write the script and then running it from the terminal.
  • Permissions: Before a bash script can be executed, it needs to have the appropriate permissions. Use the chmod command to make your script executable. For example, chmod +x myscript.sh will make the script named myscript.sh executable.

Hello World: Your First Bash Script

As with any programming language, the traditional “Hello, World!” program serves as a simple yet essential starting point for beginners to get acquainted with bash scripting.

To create your first bash script, open your preferred text editor and create a new file. Save the file with a .sh extension, which is conventionally used for bash script files.

Now, let’s write a basic “Hello, World!” script:


#!/bin/bash

# This is a bash script to print "Hello, World!" to the terminal
echo "Hello, World!"

In this script:

  • #!/bin/bash is known as a shebang line, which indicates the path to the bash interpreter.
  • # denotes a comment in bash scripts. Comments are ignored during script execution but are useful for providing explanations.
  • echo “Hello, World!” is the command that prints the string “Hello, World!” to the terminal.

Save the script file and navigate to its directory in your terminal. You can execute the script by typing:


./your_script_name.sh

Congratulations! You’ve just created and executed your first bash script, printing “Hello, World!” to the terminal. This simple example demonstrates the basic structure of a bash script and how to run it from the command line.

50 Bash Scripting Examples

Here is the list of 50 bash scripting example that help you to understand it better.

  1. Basic Echo Commands
  2. Using Variables
  3. Reading User Input
  4. Reading User Input (Hidden Characters)
  5. If-else Statement

Example 1: Basic Echo Commands

The echo command in Bash is used to display lines of text or string variables to the terminal window. It’s one of the simplest yet most versatile commands, suitable for displaying messages, variables, and even creating files. Here’s a basic example:


#!/bin/bash
# This script displays a greeting
echo "Hello, world!"
echo "Today is $(date)."
echo "Your current directory is: $(pwd)"
echo "Your PATH is: $PATH"

This script uses echo to print a simple greeting, the current date using the date command within $(…) for command substitution, the current working directory with pwd, and finally, the contents of the PATH environment variable. This example demonstrates how echo can be used to display text and the results of simple commands and variables.

Example 2: Using Variables

Variables in bash scripting allow you to store and reuse data. They’re essential for writing dynamic scripts where the output or behavior might change based on the input or environment. Here’s an example that demonstrates the use of variables:


#!/bin/bash
# This script uses variables to store and display information

greeting="Welcome"
user=$(whoami)
directory=$(pwd)

echo "$greeting, $user! You are currently in the directory: $directory."

In this script, greeting is a user-defined variable that stores a welcome message. The user variable captures the current user’s name using whoami, and directory holds the current directory path obtained with pwd. The echo command then uses these variables to display a personalized message. This example showcases how to define variables, assign them values, and then interpolate them in strings to display dynamic content.

Example 3: Reading User Input

Reading user input is a common task in bash scripting, allowing for interactive scripts that adapt based on user-provided data. The read command is used for this purpose. Here’s how you can use it:


#!/bin/bash
# This script reads user input and displays a personalized message

echo "Please enter your name: "
read name
echo "Hello, $name! Welcome to bash scripting."

echo "What is your favorite programming language? "
read language
echo "Great choice! $language is a lot of fun."

In this example, the script prompts the user to enter their name and favorite programming language. The `read` command waits for the user’s input, which is then stored in the name and `language` variables, respectively. The script uses these variables to display personalized messages back to the user. This example demonstrates a basic but essential interaction pattern, making scripts more dynamic and user-friendly.

Example 4: Reading User Input (Hidden Characters)

Sometimes, you might need to read sensitive user input without showing the characters typed on the screen, such as passwords. Bash’s read command can handle this with the -s flag, which hides the input. Here’s an example:


#!/bin/bash
# This script securely reads a password from the user

echo "Enter your password:"
read -s password
echo "Password accepted. Processing..."

# The script would typically proceed to validate or use the password securely

In this script, the echo command prompts the user to enter a password. The read -s password command then reads the input into the password variable without displaying the typed characters. This is crucial for maintaining security and user privacy when handling sensitive information. The example demonstrates how to securely read and handle sensitive user input in bash scripts.

Example 5: If-else Statement

The if statement in bash scripting allows for conditional execution of code blocks based on whether a specified condition is true or false. Here’s a basic example to demonstrate its usage:


#!/bin/bash
# This script checks if the user is the root user and responds accordingly

if [ $(whoami) = "root" ]; then
    echo "You are running this script as the root user."
else
    echo "You are not the root user. Please run this script with sudo."
fi

In this script, $(whoami) is used to get the current user’s name. The if statement compares this value with the string “root”. If the condition is true, it means the script is being run by the root user, and a corresponding message is displayed. If the condition is false, a different message advises the user to run the script with sudo. This example showcases the use of conditional logic to alter the flow of a script based on user permissions.

Example 6: Case Statement

The case statement in bash scripting offers a more streamlined and readable approach to handling multiple conditions based on the value of a single expression. It’s especially useful for parsing user input or the value of variables. Here’s an example:


#!/bin/bash
# This script provides a menu for the user and executes commands based on the user's choice

echo "Select an option:"
echo "1) List files"
echo "2) Print current directory"
echo "3) Exit"
read option

case $option in
  1) echo "Files in directory:" && ls ;;
  2) echo "Current directory:" && pwd ;;
  3) echo "Exiting script." && exit 0 ;;
  *) echo "Invalid option selected. Exiting." && exit 1 ;;
esac

In this script, the user is prompted to choose an option. The case statement then matches the user’s input ($option) against a list of patterns (1, 2, 3, or the wildcard * for anything else). Depending on the match, it executes a corresponding command block. This example demonstrates how to use case statements to create simple, interactive scripts with multiple choices.

Example 7: Adding Comments

Comments are essential in scripting for explaining the purpose of code, making it more readable and maintainable. In bash, comments start with the # symbol, and everything following it on the line is ignored by the interpreter. Here’s how to use them:


#!/bin/bash
# This script demonstrates the use of comments

# Define a variable
greeting="Hello" # This is an inline comment

# Display a message
echo $greeting, world! # This command prints "Hello, world!" to the terminal

# The following line is commented out and won't execute
# echo "This won't run."

echo "Script complete." # Indicate the script has finished

This script includes examples of both full-line and inline comments. Full-line comments provide explanations or instructions, while inline comments are useful for brief notes right next to a command. Adding comments like these helps others (and your future self) understand the purpose and function of your script, making code easier to follow and debug.

Example 8: Logical AND (&&)

The logical AND (&&) in bash scripting is used to execute a command or series of commands only if the previous command completes successfully. It’s a powerful way to chain commands where each depends on the success of the previous. Here’s an example:


#!/bin/bash
# This script checks for a file and then displays its contents if it exists

filename="example.txt"
[ -f "$filename" ] && echo "$filename exists." && cat "$filename"

In this script, [ -f “$filename” ] checks if the file example.txt exists. If this check succeeds, the script then uses && to chain two commands: echoing a confirmation message and displaying the file’s contents with cat.

Example 9: Logical OR (||)

The logical OR (||) in bash scripting allows the execution of a command only if the preceding command fails. This can be useful for providing alternatives or handling errors. Here’s an example:


#!/bin/bash
# This script attempts to create a directory and handles failure gracefully

dirname="new_directory"
mkdir "$dirname" || echo "Failed to create $dirname. It may already exist."

This script tries to create a directory with mkdir. If the creation fails (e.g., if the directory already exists), the script uses || to fall back to displaying an error message. This approach is handy for error handling and ensuring your script behaves predictably in various situations.

Example 10: For Loop

The for loop in bash scripting is used to execute a series of commands for each item in a list. This is particularly useful for processing sets of files or strings. Here’s an example:


#!/bin/bash
# This script demonstrates a for loop

for fruit in apple banana cherry; do
  echo "I like $fruit!"
done

In this script, the for loop iterates over a list of fruits, printing a message for each one. It’s a straightforward way to apply actions to a collection of items one by one.

Example 11: While Loop

The while loop performs a set of commands as long as the given condition is true. It’s useful for repeating actions until a certain state is reached. Here’s how you can use it:


#!/bin/bash
# This script demonstrates a while loop

counter=1
while [ $counter -le 5 ]; do
  echo "Counter is $counter"
  ((counter++))
done

This script initializes a counter and uses a while loop to print its value, incrementing the counter each time, until the counter is greater than 5.

Example 12: Reading Command Line Arguments

Command line arguments are passed to bash scripts at the time of execution and can be accessed inside the script. Here’s a basic example:


#!/bin/bash
# This script prints the first command line argument

echo "The first argument is: $1"

When running this script with an additional argument (./scriptname.sh Hello), it will print “The first argument is: Hello”, demonstrating how to access command line arguments.

Example 13: Reading Command Line (Named) Arguments

For scripts requiring more complex input, named arguments can be processed using a while loop and case statement. Here’s an example:


#!/bin/bash
# This script demonstrates reading named command line arguments

while [[ "$#" -gt 0 ]]; do
  case $1 in
    -u|--username) username="$2"; shift ;;
    -p|--password) password="$2"; shift ;;
    *) echo "Unknown parameter passed: $1"; exit 1 ;;
  esac
  shift
done

echo "Username: $username, Password: $password"

This script allows the user to specify a username and password using named arguments (e.g., ./scriptname.sh –username user –password pass). It showcases a pattern for handling named parameters, improving script usability for complex inputs.

Example 14: Reading from a File

Reading from a file in bash scripting can be done in various ways, with the while loop being one of the most common for processing each line of a file. Here’s an example:


#!/bin/bash
# This script reads each line from a file

filename='list.txt'
while IFS= read -r line; do
  echo "Line: $line"
done 

This script uses a while loop to read each line of the file specified by filename. The IFS= part prevents leading/trailing whitespace from being trimmed, and -r prevents backslash escapes from being interpreted, ensuring accurate reading of each line.

Example 15: Writing to a File

Writing to a file in bash can be achieved with redirection operators. Here’s a basic example:


#!/bin/bash
# This script writes messages to a file

echo "Hello, world!" > output.txt
echo "This is a new line." >> output.txt

The first echo command uses > to overwrite output.txt with the message, while the second echo uses >> to append another line to the file. This demonstrates how to create or overwrite a file with content and then append additional content to it.

Example 16: Check if File Exists

To check if a file exists in bash scripting, you can use the -f option in an if statement. Here's how:


#!/bin/bash
# This script checks if a file exists

filename="example.txt"
if [ -f "$filename" ]; then
  echo "$filename exists."
else
  echo "$filename does not exist."
fi

This script will notify the user whether the specified file exists or not, demonstrating a simple way to verify the existence of files before attempting operations on them.

Example 17: Check if Directory Exists

Similarly, to check if a directory exists, use the -d option. Here’s an example:


#!/bin/bash
# This script checks if a directory exists

dirname="example_dir"
if [ -d "$dirname" ]; then
  echo "$dirname exists."
else
  echo "$dirname does not exist."
fi

This script helps in confirming the existence of a directory, which is particularly useful for scripts that need to navigate file systems or manipulate directories.

Example 18: Create File if Not Exists

To create a file only if it doesn't already exist, you can use the touch command along with an if check:


#!/bin/bash
# This script creates a file if it does not exist

filename="newfile.txt"
if [ ! -f "$filename" ]; then
  touch "$filename"
  echo "$filename created."
else
  echo "$filename already exists."
fi

This script uses touch to create the file if it doesn’t exist, preventing overwriting files unintentionally.

Example 19: Create Directory if Not Exists

Creating a directory if it doesn't exist can be achieved with mkdir combined with an if check:


#!/bin/bash
# This script creates a directory if it does not exist

dirname="newdir"
if [ ! -d "$dirname" ]; then
  mkdir "$dirname"
  echo "$dirname created."
else
  echo "$dirname already exists."
fi

This script ensures that a directory is created only if it doesn't already exist, using mkdir. It’s a straightforward way to safely create directories needed for script execution.

Example 20: Sleep Command

The sleep command in bash scripting pauses the execution of a script for a specified duration, which is particularly useful for delaying actions or creating timed intervals between commands. This command can be vital in scripts that interact with resources needing time to become available or when simulating delays in automated tasks. Here’s an example demonstrating its use:


#!/bin/bash
# This script demonstrates the use of sleep for timing

echo "Starting task..."
sleep 3 # Pauses for 3 seconds
echo "Task completed after a pause."

for i in {1..5}; do
  echo "Iteration $i"
  sleep 1 # Pause for 1 second between iterations
done

echo "Script ended with timed intervals."

This script begins by announcing the start of a task, then pauses for 3 seconds before declaring the task complete. It then enters a loop, pausing for 1 second between each iteration, demonstrating how sleep can be used to control the pacing of script execution.

Example 21: Wait Command

The wait command in bash scripting pauses script execution until all background jobs have completed, or a specific job if its ID is supplied. This is essential in scripts where subsequent commands depend on the completion of background processes. Here’s how it can be effectively utilized:


#!/bin/bash
# This script demonstrates the use of wait to synchronize background tasks

echo "Starting background tasks..."
sleep 5 &
pid=$!
sleep 3 &
sleep 2 &

wait $pid # Waits only for the first sleep command to complete
echo "The longest sleep of 5 seconds is complete."

wait # Waits for all remaining background jobs to finish
echo "All background tasks are complete. Continuing with the script..."

In this example, several sleep commands are run in the background to simulate tasks. The wait command is then used twice: first to wait for the longest task (a 5-second sleep) to complete, indicated by its process ID ($pid), and then without arguments to ensure all background jobs finish before the script continues. This illustrates the wait command's utility in managing script execution flow relative to background processes.

Example 22: Working with Functions

In bash scripting, functions are blocks of code that can be repeatedly called from anywhere in the script. They help organize code into modular, reusable components. Here's a simple example of defining and using a function:


#!/bin/bash
# This script demonstrates the use of a function

greet_user() {
  echo "Hello, $1" # $1 refers to the first argument passed to the function
}

# Call the function with "Alice" as the argument
greet_user "Alice"

This script defines a function called greet_user, which takes a name as an argument and prints a greeting message. The function is then called with "Alice" as the argument, producing the output "Hello, Alice". Functions like this can make scripts more organized and readable, especially as they grow in complexity.

Example 23: Error Handling

Error handling is crucial for creating robust and reliable bash scripts that can deal with unexpected situations gracefully. In bash, error handling can be approached in various ways, including checking the exit status of commands, using the set command to control the shell's behavior upon errors, and trapping signals for cleanup actions.

A common method is to check the exit status of a command using $?, which holds the exit status of the last command executed. A zero exit status usually indicates success, while a non-zero status indicates an error.


#!/bin/bash
# Error handling example

create_directory() {
  mkdir $1
  if [ $? -ne 0 ]; then
    echo "Error: Failed to create directory $1"
    exit 1
  else
    echo "Directory created successfully."
  fi
}

create_directory "newdir"

In this example, a function attempts to create a directory. It checks the exit status of mkdir. If the command fails (perhaps because the directory already exists), it prints an error message and exits with a status of 1, indicating an error.

Example 24: Command-Line Arguments

Command-line arguments are parameters passed to a script at the time of execution. They allow users to provide input to the script without hardcoding values within the script, making scripts more flexible and reusable.


#!/bin/bash
# Command-line arguments example

echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "All Arguments: $@"
echo "Number of Arguments: $#"

This script demonstrates how to access command-line arguments. $0 is the script's name, $1, $2, etc., are the positional parameters representing the first, second, and subsequent arguments. $@ holds all arguments, and $# gives the number of arguments passed.

Example 25: String Concatenation

String concatenation in bash is straightforward and does not require a specific operator. You can concatenate strings by placing them next to each other or using variables without any spaces.


#!/bin/bash
# String concatenation example

first_name="John"
last_name="Doe"
full_name="$first_name $last_name"

greeting="Hello, $full_name!"

echo $greeting

In this example, two strings (first_name and last_name) are concatenated to form full_name. This concatenated string is then used within another string to form a greeting. Note that quotes are used around variables during concatenation to handle any spaces within the variables' values properly.

Part 2 will be posted soon...

Share.
Leave A Reply


Exit mobile version