Enhancing Flexibility with Command-Line Arguments and User Inputs
Making Bash scripts interactive by handling command-line arguments and user inputs allows you to create more flexible and user-friendly scripts. By processing inputs, your scripts can adapt their behavior based on parameters or prompts provided during execution. This part covers how to accept and handle command-line arguments, use the read command for user input, and validate input data.
Using Command-Line Arguments
Command-line arguments are parameters passed to a script when it is executed. In Bash, these arguments are represented as special variables:
$0: The name of the script.
$1, $2, ...: The first, second, and subsequent arguments.
$#: The number of arguments passed to the script.
$@ and $*: All arguments.
Example: Simple Command-Line Argument Handling
#!/bin/bash
# greet.sh - Greet a user with their name passed as an argument
if [ $# -eq 0 ]; then
echo "Usage: $0 <name>"
exit 1
fi
name=$1
echo "Hello, $name! Welcome to Bash scripting."
Explanation:
The script checks if any arguments are passed using $#. If no arguments are provided, it displays a usage message and exits. If an argument is provided, it greets the user using the first argument ($1).
Using Multiple Command-Line Arguments
You can handle multiple arguments by accessing $2, $3, and so on.
Example: Summing Two Numbers
#!/bin/bash
# sum.sh - Sum two numbers passed as arguments
if [ $# -ne 2 ]; then
echo "Usage: $0 <number1> <number2>"
exit 1
fi
num1=$1
num2=$2
sum=$((num1 + num2))
echo "The sum of $num1 and $num2 is $sum."
Explanation:
The script expects exactly two arguments. It reads the values of $1 and $2 as num1 and num2. It calculates their sum and prints the result.
Iterating Over Command-Line Arguments
You can use a for loop to process all arguments.
Example: Printing All Arguments
#!/bin/bash
# print_args.sh - Print all arguments passed to the script
echo "You passed $# arguments."
for arg in "$@"; do
echo "Argument: $arg"
done
Explanation:
$# gives the number of arguments. $@ represents all arguments, allowing the loop to iterate over each.
Using the read Command for User Input
The read command allows you to prompt the user for input during script execution.
Example: Prompting for User Input
#!/bin/bash
# ask_name.sh - Prompt the user for their name
read -p "Enter your name: " name
echo "Hello, $name!"
Explanation:
read -p displays a prompt and waits for user input, storing it in the variable name. The user’s input is then printed using echo.
Example: Reading a Password Securely
#!/bin/bash
# ask_password.sh - Prompt for a password without displaying input
read -sp "Enter your password: " password
echo
echo "Your password is stored securely."
Explanation:
The -s option hides the user input, useful for passwords or sensitive data. echo is used to add a newline after input.
Validating and Processing User Input
Validating user input is crucial for ensuring your scripts behave as expected.
Example: Validating Numerical Input
#!/bin/bash
# validate_number.sh - Check if input is a number
read -p "Enter a number: " input
if [[ "$input" =~ ^[0-9]+$ ]]; then
echo "You entered a valid number: $input"
else
echo "Invalid input. Please enter a number."
fi
Explanation:
The [[ ... ]] syntax is used for pattern matching. ^ indicates the start of the string, [0-9]+ matches one or more digits, and $ indicates the end of the string.
Example: Menu-Based Script Using User Input
#!/bin/bash
# menu.sh - Simple menu-based script
echo "Select an option:"
echo "1. Display date and time"
echo "2. List files"
echo "3. Exit"
read -p "Enter your choice [1-3]: " choice
case $choice in
1)
echo "Current date and time: $(date)"
;;
2)
echo "Listing files:"
ls
;;
3)
echo "Exiting."
exit 0
;;
*)
echo "Invalid choice. Please enter a number between 1 and 3."
;;
esac
Explanation:
The script presents a menu to the user. It uses read to capture the user’s input. A case statement handles different choices, providing a simple interactive experience.
Combining Command-Line Arguments and User Input
Scripts can handle both command-line arguments and user inputs together.
Example: File Operation Script
#!/bin/bash
# file_operations.sh - Perform operations on a file
if [ $# -eq 0 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
filename=$1
if [ ! -e "$filename" ]; then
echo "File $filename does not exist. Would you like to create it? (yes/no)"
read answer
if [ "$answer" == "yes" ]; then
touch "$filename"
echo "File $filename created."
else
echo "Operation canceled."
fi
else
echo "File $filename already exists."
fi
Explanation:
The script expects a filename as an argument. If the file does not exist, it prompts the user to create it. This combines argument handling and user input for interactive behavior.
Handling command-line arguments and user input in Bash scripts enables you to build flexible, user-friendly, and dynamic scripts. You’ve learned how to accept arguments, use the read command for prompts, validate inputs, and create interactive menus. By leveraging these techniques, you can develop scripts that adapt to user needs and handle varying input scenarios efficiently.