User Interaction and Real World Bash
User Interaction and Real World Bash
user-interaction.pdf
3. Options
while getopts u:p: option; do
case ${option} in
u) user=$OPTARG;;
p) pass=$OPTARG;;
esac
done
echo "user:$user / pass: $pass"In our script, we can use the getopts keyword. We specify an opt string (option string) that defines the search criteria.
Here, we utilize u:p:. This means the script will have -u and -p options. A colon after each option indicates that the script expects an argument for each.
Within the loop, we assign each option to the variable option and utilize it in a case statement.
The OPTARG variable holds the argument value for each option.
Then, we finish our script with an echo statement, and save.
while getopts :u:p:ab option; do
case $option in
u) user=$OPTARG;;
p) pass=$OPTARG;;
a) echo "got the A flag";;
b) echo "got the B flag";;
?) echo "I don't know what $OPTARG is!";;
esac
done
echo "user:$user / pass: $pass"Adding a question mark ? will capture these unknown options in the case statement.
5.Input During Execution
6. Responding
**Using the -i option with the read command allows us to suggest a response for the user. If the user presses return without entering a response, the suggested response will be used by default.
We can use a regular expression to check whether:
the input
$zipcodematches a 5-digit pattern
{5}containing digits
[0-9]
When the condition is true, the loop stops and the program carries on.
7. Discovery 1
**1. Use the read command to request user input and return only after reading exactly 55 characters
Solution: The -N numOfChar returns only after reading exactly numOfChar characters, unless EOF is encountered or read times out.
read -N 5
The -n option allows us to define a character limit for a response.
The -t option allows us to limit the amount of time taken to input text.
In Bash scripting, set -x is a command that enables the debugging mode, where the shell will print each command before it's executed. This is useful for understanding the flow of a script and debugging any issues.
Here's a simple example to demonstrate how set -x works: