30 Bash Script Examples
In this article, we will explore 30 practical and easy-to-understand examples of Bash scripts, along with detailed explanations and code snippets.
Hello World
Let's start with a classic example - the "Hello World" script. Open your favorite text editor and create a new file called hello.sh
. Type the following code:
#!/bin/bash
echo "Hello, World!"
Save the file and open your terminal. Navigate to the directory where you saved the script and run the following command:
bash hello.sh
The script will print "Hello, World!" to the terminal.
Variables and User Input
Bash allows you to declare variables and interact with users. Here's an example that prompts the user for their name and then displays a personalized greeting:
#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name! Nice to meet you."
Arithmetic Operations
Bash can perform basic arithmetic operations. Let's create a script that adds two numbers:
#!/bin/bash
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
sum=$((num1 + num2))
echo "The sum is: $sum"
Conditional Statements
Conditional statements allow you to perform different actions based on certain conditions. Here's an example that checks if a number is positive, negative, or zero:
#!/bin/bash
echo "Enter a number:"
read num
if ((num > 0)); then
echo "The number is positive."
elif ((num < 0)); then
echo "The number is negative."
else
echo "The number is zero."
fi
Loops
Loops are used to repeat a block of code multiple times. Here's an example of a for
loop that prints the numbers from 1 to 5:
#!/bin/bash
for ((i=1; i<=5; i++)); do
echo $i
done
File Operations
Bash provides powerful tools for working with files. Let's create a script that checks if a file exists and displays its content if it does:
#!/bin/bash
echo "Enter a file name:"
read -r filename
if [ -f $filename ]; then
echo "File exists. Here is its content:"
cat $filename
else
echo "File not found."
fi
String Manipulation
Bash allows you to manipulate strings easily. Here's an example that converts a string to uppercase:
#!/bin/bash
echo "Enter a string:"
read input
uppercase=$(echo $input | tr '[:lower:]' '[:upper:]')
echo "Uppercase: $uppercase"
Command-Line Arguments
You can pass arguments to a Bash script when running it from the command line. Here's an example that prints all the arguments passed to the script:
#!/bin/bash
echo "Arguments: $@"
Save the script as args.sh
and run it with the following command:
bash args.sh arg1 arg2 arg3
The script will output: "Arguments: arg1 arg2 arg3".
Functions
allowFunctions you to group code and reuse it. Here's an example of a function that calculates the factorial of a number
#!/bin/bash
factorial() {
local n=$1
if [ $n -eq 0 ]; then
return 1
else
return $(($n * $(factorial $(($n-1)))))
fi
}
Here's an example usage of the function:
$ factorial 5
120
Environment Variables
Bash provides access to various environment variables that hold information about the system. Here's an example that displays the current user's username:
#!/bin/bash
echo "Current user: $USER"
Exit Status
Every command in Bash returns an exit status. A of 0 value indicates success, while non-zero values indicate failure. Here's an example that checks the exit status of a command:
#!/bin/bash
ls
if [ $? - eq0 ]; then
echo "Command executed successfully."
else
echo "Command failed."
fi
Reading from a File
Bash allows you to read data from a file and process it. Here's an example that reads a file line by line and displays its content:
#!/bin/bash
echo "Enter a file name:"
read filename
while IFS= read -r line; do
echo "$line"
done < $filename
Writing to a File
You can also write data to a file using Bash. Here's an example that prompts the user for input and saves it to a file:
#!/bin/bash
echo "Enter some text:"
read input
echo $input > output.txt
echo "Text saved to output.txt"
Command Substitution
Bash allows you to execute a command and use its output as part of another command. Here's an example that counts the number of files in a directory:
#!/bin/bash
count=$(ls | wc -l)
echo "Number of files: $count"
Redirecting Output
You can redirect the output of a command to a file or another command. Here's an example that redirects the output of a command to a file:
#!/bin/bash
ls > files.txt
echo "Output redirected to files.txt"
Pipes
Pipes allow you to connect multiple commands together, with the output of one command serving as the input for the next. Here's an example that lists the files in a directory and sorts them alphabetically:
#!/bin/bash
ls | sort
Arrays
Bash supports arrays, which allow you to store multiple values in a single variable. Here's an example that declares an array and prints its elements:
#!/bin/bash
fruits=("Apple" "Banana" "Orange")
echo "Fruits: ${fruits[@]}"
Case Statement
The case statement is useful for performing different actions based on multiple conditions. Here's an example that checks the day of the week:
#!/bin/bash
# Set the day of the week
day=$(date +%u)
# Use a case statement to perform different actions based on the day of the week
case $day in
# Monday
1) echo "It's Monday!";;
# Tuesday
2) echo "It's Tuesday!";;
# Wednesday
3) echo "It's Wednesday!";;
# Thursday
4) echo "It's Thursday!";;
# Friday
5) echo "It's Friday!";;
# Saturday
6) echo "It's Saturday!";;
# Sunday
7) echo "It's Sunday!";;
esac
Process Management
Bash allows you to manage processes on your system. Here's an example that lists all running processes:
#!/bin/bash
ps -ef
File Permissions
Bash provides tools for managing file permissions. Here's an example that changes the permissions of a file to read-only:
#!/bin/bash
echo "Enter a file name:"
read filename
chmod 400 $filename
String Comparison
Bash allows you to compare strings for equality or alphabetical order. Here's an example that compares two strings:
#!/bin/bash
string1="Hello"
string2="World"
if [ $string1 == $string2 ]; then
echo "The strings are equal."
else
echo "The strings are not equal."
fi
Math Operations
Bash can perform various mathematical operations. Here's an example that calculates the square root of a number:
#!/bin/bash
echo "Enter a number:"
read num
sqrt=$(awk "BEGIN { print sqrt($num) }")
echo "Square root: $sqrt"
Networking
Bash provides tools for networking tasks. Here's an example that pings a remote server:
#!/bin/bash
echo "Enter a hostname or IP address:"
read host
ping -c 4 $host
String Length
You can determine the length of a string using Bash. Here's an example that prints the length of a#!/bin string:
#!/bin/bash
echo "Enter a string:"
read input
length=${#input}
echo "Length: $length"
Random Numbers
Bash can generate random numbers. Here's an example that generates a random number between 1 and 100:
#!/bin/bash
random=$(shuf -i 1-100 -n 1)
echo "Random number: $random"
Cron Jobs
Cron jobs allow you to schedule tasks to run at specific times. Here's an example that runs a script every day at 8:00 AM:
#!/bin/bash
echo "0 8 * * * bash script.sh" | crontab -
echo "Cron job created."
Error Handling
Bash allows you to handle errors and exceptions. Here's an example that catches errors and displays a custom message:
#!/bin/bash
command_that_may_fail
if [ $? -ne 0 ]; then
echo "An error occurred."
fi
Sending Email
Bash can send email using the mail
command. Here's an example that sends an email:
#!/bin/bash
echo "Subject: Test Email" | mail -s "Test Email" user@example.com
echo "Email sent."
Regular Expressions
Bash supports regular expressions for pattern matching. Here's an example that checks if a string matches a pattern:
#!/bin/bash
echo "Enter a string:"
read input
if [[ $input =~ ^[0-9]+$ ]]; then
echo "The string contains only digits."
else
echo "The string does not contain only digits."
fi
Exiting a Script
You can exit a Bash script at any point using the exit
command. Here's an example that exits the script if a condition is not:
#!/bin/bash
# Check if the input parameter is not empty
if [[ -z $1 ]]; then
echo "Error: No input parameter provided"
exit 1
fi
# Do something with the input parameter
echo "Processing input parameter: $1"
Congratulations! You have explored 30 practical examples of Bash scripts. These examples cover a wide range of topics, from basic operations to more advanced concepts. By understanding and mastering these examples, you will be well-equipped to automate tasks and streamline your workflow using Bash scripting.
Further Reading
📝 Written by Haikel Fazzani
📝 Latest Blog Posts
Stay updated on the world of software development with our fresh articles and expert insights.
Top 10 Docker Commands: A Beginner's Guide
Learn the fundamental Docker commands to build, manage, and deploy containerized applications. This comprehensive guide covers everything from basic operations to advanced techniques.
Fetch API Abort Controller in JavaScript
Learn how to use the Fetch API Abort Controller in JavaScript to cancel and timeout requests, and take control of your asynchronous requests like never before.
Handling Preflight Requests in Deno
Learn how to handle preflight requests in Deno applications using TypeScript. This guide explains CORS, preflight requests, and provides a step-by-step tutorial to set up a server that manages cross-origin interactions seamlessly.
Understanding AES Encryption Modes: AES-GCM, AES-CBC, AES-CTR
Explore the differences between AES-GCM, AES-CBC, and AES-CTR encryption modes. Learn when to use each, along with a comparison of performance, key size, resource usage, and usage scenarios.