Command-Line Arguments in Shell Scripts Examples

Explore practical examples of using command-line arguments in shell scripts to enhance your scripting skills.
By Jamie

Introduction to Command-Line Arguments in Shell Scripts

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.

Example 1: Simple File Backup Script

Context

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"

Notes

  • Ensure that the destination directory exists before running the script.
  • You can add error handling to check if the source file exists before attempting to back it up.

Example 2: User Greeting Script

Context

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."

Notes

  • You can enhance this script by adding an optional argument for the user’s favorite color and including that in the greeting.
  • Consider adding input validation to ensure that age is a number.

Example 3: Log File Analysis Script

Context

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."

Notes

  • You can enhance the script by allowing for case-insensitive searches by adding the -i option to the grep command.
  • Consider redirecting the output to a file for further analysis.