Gather User Input

Download PDF

Gather User Input in Your BASH Shell Script

Gather User InputWelcome to my blog how we can gather user input within our BASH shell scripts. We will be making great use of the built-in command read and your scripts will be awesome. We start with a quick demonstration of an example script. When the script runs we are prompted for the name of the user. We can then check to see if the use already exists before creating the user. Simple but shows read off really well.


As with everything that we can do with a shell script we can also run read direct from the command line to test. So, for example if we want to demonstrate how to gather user input from the command line:

read -p "Enter a user name: "

As we have not specified the variable name to use whatever we enter will populate the variable $REPLY. Should we want to specify out own variable name, which makes better sense especially for longer scripts:

read -p "Enter a user name: " username

Here we will populate a variable of our own choice called username in this example.

The option -p is for the prompt. Other options include

  • -s: To suppress the screen output such as for passwords
  • -n: To limit the number of characters that can be added. For example we might have -n2 where we prompt for a US state.

The script we use in the video is shown below. Note that in the if statement we use the exit command to leave the script if the user already exists:

read -p "Enter a name for the user: " username

if grep -q $username /etc/passwd
then
 echo "The user $username already exists"
 exit 1
fi
 
sudo useradd -m $username

As always we include a video which we hope you will follow.

My Book on Shell Scripting is available from good book shops and the publisher Packt.

shellscripting