7.4. User Input & Arguments#
Make scripts interactive by accepting arguments and reading user input.
7.4.1. Real-World Example: Interactive Configuration#
#!/bin/bash
# Validate we got a config file
if [ $# -ne 1 ]; then
echo "Usage: $0 <config_file>"
exit 1
fi
config_file="$1"
echo "=== System Configuration ==="
echo
# Check if config exists
if [ -f "$config_file" ]; then
read -p "Config exists. Overwrite? (y/n): " overwrite
if [ "$overwrite" != "y" ]; then
echo "Aborted"
exit 0
fi
fi
# Get configuration from user
read -p "Hostname: " hostname
read -p "IP Address: " ip_addr
read -p "Gateway: " gateway
# Validate IP
if ! [[ "$ip_addr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "Invalid IP address"
exit 1
fi
# Save configuration
cat > "$config_file" << EOF
hostname=$hostname
ip_addr=$ip_addr
gateway=$gateway
EOF
echo "Configuration saved to $config_file"
7.4.1.1. read Multiple Variables#
#!/bin/bash
read -p "Enter first and last name: " first last
echo "First: $first"
echo "Last: $last"
Usage:
$ bash myscript.sh
Enter first and last name: John Doe
First: John
Last: Doe
7.4.1.2. read from File or Pipe#
#!/bin/bash
# Read from file
while read -r line; do
echo "Read: $line"
done < /etc/hostname
# Read from pipe
echo "hello world" | read first second
echo "$first $second" # "hello world"
7.4.1.3. Basic read#
#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name!"
Usage:
$ bash myscript.sh
What is your name?
Alice
Hello, Alice!
7.4.1.4. read with Prompt#
#!/bin/bash
read -p "Enter username: " username
read -p "Enter password: " password
echo "Logged in as: $username"
7.4.1.5. read -s: Silent (Password)#
#!/bin/bash
read -sp "Enter password: " password
echo
echo "Password accepted (length: ${#password})"
The -s flag hides input (no echo)
7.4.2. read: Interactive Input#
Get input from user during script execution:
7.4.2.1. Validating Arguments#
#!/bin/bash
# Check if argument provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
# Check if too many arguments
if [ $# -gt 2 ]; then
echo "Too many arguments"
exit 1
fi
# Check specific argument count
if [ $# -ne 2 ]; then
echo "Exactly 2 arguments required"
exit 1
fi
echo "Arguments: $1, $2"
Usage:
$ bash myscript.sh
Usage: ./myscript.sh <filename>
$ bash myscript.sh a b c
Too many arguments
$ bash myscript.sh a b
Arguments: a, b
7.4.2.2. Accessing Arguments#
#!/bin/bash
# $0 = script name
echo "Script: $0"
# $1, $2, $3... = first, second, third argument
echo "First arg: $1"
echo "Second arg: $2"
# $# = total number of arguments
echo "Total args: $#"
# $@ = all arguments (as array)
echo "All args: $@"
# $* = all arguments (as string)
echo "As string: $*"
Usage:
$ bash myscript.sh foo bar baz
Script: ./myscript.sh
First arg: foo
Second arg: bar
Total args: 3
All args: foo bar baz
As string: foo bar baz
7.4.3. Script Arguments: \(@, \)#, \(0-\)9#
Access command-line arguments passed to script: