SECTION 4
REQUESTING
USER INPUT
SECTION CHEAT SHEET
POSITIONAL PARAMETERS
The shell assigns numbers called positional parameters to
each command-line argument that is entered. ($1, $2, $3…)
Example Script:
myscript Tom /home/Tom red
#!/bin/bash
echo “My Name is $1”
echo “My home directory is $2”
echo “My favourite colour is $3”
SPECIAL PARAMETERS
Special parameters are like regular parameters, but are
created for us by the shell, and are unmodifiable
Special Parameter
Description Command
Parameter Value for
Line
Command Line
Stores the number of [Link] 1 2 3 3
$# command line arguments
provided to the script
$0 Stores the script name [Link] 1 2 3 [Link]
Expands to each [Link] "daily reports" daily reports
$@ positional parameter as (2 words)
its own word with
subsequent word splitting
Expands to each daily reports
“$@” [Link] "daily reports"
positional parameter as (1 word)
its own word without
subsequent word splitting
$* Exactly the same as $@ [Link] "daily reports" daily reports
(2 words)
Expands to all positional IFS=, daily,reports
“$*” parameter as one word [Link] “daily reports” (1 word)
separated by the first
letter of the IFS variable
without subsequent word
splitting
$? Gives the exit code echo “hello” 0
returned by the most echo $? (because echo “hello”
recent command was successful)
THE READ COMMAND:
The read command asks for input from the user and saves
this input into a variable
Syntax for the read command:
read variable
OPTIONS
Displays a prompt to user about what information
-p “prompt”
they must enter
-t time Timeout if the user does not enter any value within
time seconds.
-s Prevent the input that the user enters from being
shown in the terminal. The “secret” option.
-N chars Limit the users response to exactly chars characters
-n chars Limit the users response to a maximum of
chars characters
Example Script:
#!/bin/bash
read -t 5 -p "Input your first name within 5 seconds: " name
read -n 2 -p "Input your age (max 2 digits): " age
read -s -N 5 -p "Enter your zip code (exactly 5 digits): " zipcode
echo "$name, $age, $zipcode" >> [Link]
THE SELECT COMMAND
The select command provides the user with a dropdown
menu to select from. The user may select an option from
a list of options.
It is also possible to provide a prompt to a user using the
PS3 shell variable.
Syntax for the select command:
PS3="Please select an option below: "
select variable in options ; do
commands...
break
done
Example Script:
#!/bin/bash
PS3="What is the day of the week?: "
select day in mon tue wed thu fri sat sun ; do
echo "The day of the week is $day"
break
done