How to Handle and Read User Input in Bash
Introduction
Handling user input in Bash enables you to collect, store, and process specific options, commands, or values to execute specific tasks. You can capture and handle user input in Bash using the following options:
read
: Allows Bash to interactively capture user input and store the result in a variable.command-line options
: Handles positional parameters such as$1
,$2
, and$3
depending on the option's position. Command-line options can also include flags such as-h
for help, or-v
depending on a Bash script's functionalities.Getopts
: Provides a powerful, structured way to handle command-line options and arguments in a script.Getopts
provides advanced functionalities by decoding the user input to specific actions defined in a script. This is important when handling user input with loops or conditional statements.
This article explains how to handle and process user input in Bash using the read
, command-line options
, and getopts
commands.
Read Command
The read
command in Bash captures user input and stores the result in a variable. You can retrieve the variable's value to view or manipulate the user input using commands such as echo
, conditional statements, or loops in a script. read
uses the following command syntax.
read variable
In the command, read
prompts for user input and variable
stores the input value.
Create a new
read-command.sh
file.console$ nano read-command.sh
Add the following Bash script contents to the file.
bash#!/bin/bash echo "What is your name?" read username echo "Hello there $username"
Save and close the file.
The above script uses the
read
command to prompt for a user input and stores the captured data into thename
variable. Theecho
command retrieves thename
variable's value and displays it in the output.Run the script using Bash.
console$ bash read-command.sh
Enter a name such a
John Doe
.What is your name?
Output:
What is your name? John Doe Hello there John Doe
Command-Line Options
Command-line options are positional parameters you can pass to a Bash script when executing a command. Positional parameters follow strict order special number variables to capture the user input and parse it to a script for processing as follows:
$0
: Refers to the Bash script itself.$1
: Represents the first argument passed to the script.$2
: Represents the second argument passed to the script.$3
: Represents the third argument passed to the script.
Optional flags modify a Bash script's behavior and start with a hyphen -
or double-hyphen --
depending on the script's logic. For example:
-h
-v
--help
Command-line options in Bash use the following syntax.
script <options> [args]
For example, create a new
opts-test.sh
file.console$ nano opts-test.sh
Add the following Bash script contents to the file.
bash#!/bin/bash case $1 in John) echo "Hello $1, your username is, $2_admin" ;; Admin) echo "Hello $1, your username is $2_superuser" ;; *) echo "You did not enter a valid option" ;; esac
Save and close the file.
The above script uses a switch case statement to process the user input depending on the command-line options parsed to the script and outputs a result.
Run the Bash script with a command-line option such as
John Doe
.console$ bash opts-test John Doe
Output:
Hello John, your username is, Doe_admin
The Bash script processes the user input
John
as$1
andDoe
as$2
to compare the value with a list of patterns in thecase
statement to execute theecho
command after finding a match.Run the Bash script without any options.
console$ bash opts-test John Doe
Output:
You did not enter a valid option
GetOpts
getopts
is a Bash command that manages command line options and arguments during execution. getopts
handles flags and options in a structured style to execute specific contents or handle errors in a script. The getopts
command uses the following syntax in Bash.
getopts options opt [args]
In the above getopts
command:
options
: A string that specify the script's options or arguments. The command expects arguments if a character is followed by a colon:
. For example,hello:world
enables the command to search for arguments where-hello
requires an argument and-world
does not require. Options defined in one form do not require arguments. For example,helloworld
instructs the command to search for the options-hello
,-world
without any arguments.opt
: A variable that stores the current option being processed in thegetopts
command. You can use any variable names butopt
andoption
are natively used as variables in thegetopts
command.[args]
: Optional arguments parsed to the script instead of positional parameters in thegetopts
command. Options that include:
require an argument. For example, in:a:b
,a
requires an argument andb
does not require any arguments due to a missing colon:
after the option.
The getopts
command commonly works with loops such as while
to process all options in a script. Conditional statements such as case
also perform different actions depending on the current option processed by getopts
.
Use getopts
Without Arguments
Create a new
getopts.sh
file.console$ nano getopts.sh
Add the following Bash script contents to the file.
bash#!/bin/bash while getopts ":an" opt; do case $opt in a) echo "The first option $1 is selected" ;; n) echo "The second option $1 is selected" ;; \?) echo "Invalid option selected" exit 1 ;; esac done
Save and close the file.
The above script uses the
getopts
command to handle the-a
and-n
command-line options. The script then processes the current option using acase
statement to output a specific message that matches a pattern. The messageInvalid option selected
displays and the script terminates with an exit status of1
if you provide an invalid option.Run the script with a valid option such as
-a
.console$ bash getopts.sh -a
Output:
The first option -a is selected
Run the script with an invalid option such as
-g
.console$ bash getopts.sh -g
Output:
Invalid option selected
Query the exit status of the last executed command.
console$ echo $?
Output:
1
Use getopts
with Arguments
Create a new
getopts_args.sh
file..console$ nano getopts_args.sh
Add the following Bash script contents to the file.
bash#!/bin/bash while getopts ":a:n:" opt; do case $opt in a) echo "The first option $1 is selected" ;; n) echo "The second option $1 is selected" ;; \?) echo "Invalid option selected" exit 1 ;; esac done
Save and close the file.
The above script uses the
getopts
command to handle thea
andn
command-line options that require arguments to process the user input using acase
statement to output a specific message that matches a pattern. The variableOPTARG
is a built-ingetopts
variable that stores arguments. The script terminates if the user input contains an invalid or empty argument.Run the script using Bash with an option such as
-a
and the argumentlamp
.console$ bash getopts_args.sh -a lamp
Output:
The first option -a is selected
Handle and Read User Input in Bash Scripts Using Read, Options, and GetOpts
You can combine read
, command-line options
, and getopts
to capture, handle and process user input in a structured way in Bash. This is useful when creating applications that require specific options and arguments to perform specific tasks. Follow the steps below to create a Bash script that installs a web server stack on a Linux system based on the user input choices.
Create a new
example.sh
file.console$ nano example.sh
Add the following Bash script contents to the file.
bash#!/bin/bash echo -n "What's your name: " read user_name echo "Hello, $user_name. Running your command-line option in a loop." while getopts "s:h-" opt; do case $opt in s) case $OPTARG in -n | lemp) echo "You can install LEMP using the command 'sudo apt install -y nginx mysql-server php php-fpm'." echo "Run this command, yes|no?" read user_decision if [[ $user_decision == "yes" ]]; then sudo apt update sudo apt install -y nginx mysql-server php php-fpm echo "LEMP stack installed!" else echo "LEMP not installed." exit 0 fi ;; -a | lamp) echo "You can install LAMP using the command 'sudo apt install -y apache2 mysql-server php php-mysql'." echo "Run this command, yes|no?" read user_decision if [[ $user_decision == "yes" ]]; then sudo apt update sudo apt install -y apache2 mysql-server php libapache2-mod-php php-mysql echo "LAMP stack installed!" else echo "LAMP not installed." exit 0 fi ;; *) echo "Invalid option. Please choose 'lemp' or 'lamp'." echo "Usage: $0 -s [lemp|lamp] or --stack [lemp|lamp] [-h|--help]" echo "" echo "Allowed Options:" echo " -s, --stack Specify the stack to install (lemp or lamp)" echo " -h, --help Show this help screen" exit 1 ;; esac ;; h) echo "Usage: $0 -s [lemp|lamp] or --stack [lemp|lamp] [-h|--help]" echo "" echo "Allowed Options:" echo " -s, --stack Specify the stack to install (lemp or lamp)" echo " -h, --help Show this help screen" exit 0 ;; -) case $OPTARG in help) echo "Usage: $0 -s [lemp|lamp] or --stack [lemp|lamp] [-h|--help]" echo "" echo "Allowed Options:" echo " -s, --stack Specify the stack to install (lemp or lamp)" echo " -h, --help Show this help screen" exit 0 ;; *) echo "Invalid option. Run -h or --help to display the available options." exit 1 ;; esac ;; *) echo "Invalid option. Run -h or --help to display the available options." exit 1 ;; esac done if [[ $OPTIND -eq 1 ]]; then echo "No options provided." echo "Usage: $0 -s [lemp|lamp] or --stack [lemp|lamp] [-h|--help]" echo "" echo "Allowed Options:" echo " -s, --stack Specify the stack to install (lemp or lamp)" echo " -h, --help Show this help screen" exit 1 fi
Save and close the file.
The above script prompts the user to input an option
-s
with a web stack name in either a short or long format such as-a or --apache
.getopts
handles the command-line options and uses awhile
loop to compare the result against a list of patterns in acase
statement and executes specific commands after finding a match. The nestedcase
statement compares the argument against another list of patterns, prompts for user confirmation, and stores the value in auser_decision
variable using theif-else
statement. Theecho
command displays a result after finding a match and the condition evaluates totrue
.Run the script using Bash, specify the
-s
option, and thelemp
argument.console$ bash example.sh -s --lemp
Enter a name like
John Doe
when prompted.What's your name:
The script outputs the following result after finding a match. Enter
no
when prompted to install the web stack.Hello, John Doe. Running your command-line option in a loop. You can install LEMP using the command 'sudo apt install -y nginx mysql-server php php-fpm'. Run this command, yes|no? no LEMP not installed.
Run the script again and specify the
-h
option to view the help page.console$ bash example.sh -h
Output:
Usage: example.sh -s [lemp|lamp] or --stack [lemp|lamp] [-h|--help] Allowed Options: -s, --stack Specify the stack to install (lemp or lamp) -h, --help Show this help screen
Conclusion
You have handled and processed user input in Bash using the read
command, command-line options
, and getopts
. User input allows using multiple options when executing specific commands that require user action. You can integrate user input commands such as getopts
with loops or conditional statements such as if-else
to filter options and run specific tasks in Bash.