Bash Scripting Tutorial #3: User Input

User prompting can be done in at least a couple of different ways in bash. User prompting is useful when you are drafting a project or an important scripting job for someone else to use to successfully complete a task. When collecting user input, the input is placed in a variable(see last article) and then the value of the variable is implied when the variable is called later in the script. Multiple variables can be specified in the read line, this will allow for more than one answer to the script’s question. Some examples of situations where this would be useful would be when your client needs to sort and review large text files or spreadsheets by the information in the files. Linux has commands for sifting through and sorting data, but to appy it in a script, the script has to know what files to look through and what to do with said information. Another useful example is when creating a simple bash cli game to pass time at work when you should really be doing something but you’re just not feeling it. Also, this technique is useful when collecting and parsing information about a client or employee. A simple example would be the following:

echo “Enter your name”

read name

echo “Enter your birthday”

read birthday

echo “Hello” $name “your birthday is” $birthday

Where as name and birthday would be the information you entered when prompted. This is known as a sequence of STDIN and STDOUT or standard input and standard output(Input being what you entered and Output being what was pritned to the screen after all the information had been gathered). Another prime example would be merely using a read line like:

read -p “Enter a series of potential baby names”: name1 name2 name3 name4

cat $name1 >> babynames.txt

cat $name2 >> babynames.txt

cat $name3 >> babynames.txt

cat $name4 >> babynames.txt

This script will prompt the user for babynames that they are considering and will simply save them to a list of names in a file called babynames.txt. In this we are redirecting the STDOUT to another file rather than displaying them to the screen briefly before losing them. This, unfortunately only allows for four names. To add four new names or one name over multiple iterations, one would most likely want to use the first method in a loop(more about these later). Next we will be looking at if statements.

These guys have even more useful examples:

https://bash.cyberciti.biz/guide/Getting_User_Input_Via_Keyboard

Leave a Reply