Command-line arguments are a powerful feature in shell scripting that allow users to pass information to scripts at runtime. This feature enhances the flexibility and usability of scripts, making them adaptable to various needs without modifying the code itself. Here are three practical examples that demonstrate how to effectively use command-line arguments in shell scripts.
This script creates a backup of a specified file. It takes the original file’s name and the backup destination as command-line arguments, making it easy to back up different files without changing the script.
#!/bin/bash
# Check if the correct number of arguments is provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <file_to_backup> <backup_destination>"
exit 1
fi
# Assign command-line arguments to variables
file_to_backup="$1"
backup_destination="$2"
# Create a backup
cp "$file_to_backup" "$backup_destination"
echo "Backup of $file_to_backup created at $backup_destination"
This script greets a user by name and age. It takes the user’s name and age as command-line arguments, allowing for personalized greetings without modifying the script.
#!/bin/bash
# Check for the correct number of arguments
if [ $# -ne 2 ]; then
echo "Usage: $0 <name> <age>"
exit 1
fi
# Assign command-line arguments to variables
name="$1"
age="$2"
# Display greeting message
echo "Hello, $name! You are $age years old."
This script analyzes a log file and counts the occurrences of a specific error type passed as a command-line argument. It is useful for system administrators looking to quickly assess log files.
#!/bin/bash
# Check if the correct number of arguments is provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <log_file> <error_type>"
exit 1
fi
# Assign command-line arguments to variables
log_file="$1"
error_type="$2"
# Analyze the log file for the specified error type
count=$(grep -c "$error_type" "$log_file")
# Display the result
echo "The error '$error_type' occurred $count times in $log_file."
-i
option to the grep
command.