Categories
Linux Tutorial Series

Linux Tutorial Series – 194 – Reading user input

Here is the video version, if you prefer it:

You can read user input in shell scripts. (Ward, 2014)⁠

Here is an example of a script which reads user input:

#!/bin/bash

read name

echo "My name is $name"

Notice how I used the double quotes to make the shell expand my variable. My variable, by the way, is called name. read name prompts the user for input and when the user inputs the information (and presses Enter), that input is stored in the variable named name.

Here is how it works:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh

Mislav

My name is Mislav

As you already know, you can read user input through arguments that you pass to your shell script. I don’t know which way is the better way and which way is more idiomatic to the shell, but I’d opt for passing values as arguments to the script and then doing checks on the arguments at the beginning of the script. You can also do these checks after reading something in a variable (such as “Is the string that the user inputted empty?”), but I think that doing these checks after each read is tedious; much better to do them at the beginning of the script. Again, not certain which way is idiomatic to the shell and both exist so both must be fine, but I am unsure.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 269

NewsletterUpdates on interesting things I am doing

Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.

Leave a Reply

Your email address will not be published. Required fields are marked *