Share via:

Reading User Input in Bash

How to read user input from shell scripts using the read command.

88 views

Edited: 2019-12-11 11:16

Accept user input, bash

In shell scripting, we might want to read input from the user, and perform conditional execution of code depending on what the input was. Other times we might just want to feed the input to a system command.

Whatever the case is, we can accept user input using the read command. By including the -e option, we can even allow the user to use the TAB key to complete file paths, just like they would when using the terminal normally.

A short example script is shown below:

#!/bin/sh

printf "\n  Please type your username:\n\n"
read userName

if [ "$userName" = "" ]
then
  printf "\nYou did not provide a user name, you ass clown!\n\n"
else 
  printf "\n\nHallo $userName""\n\n"
fi

Accepting file system paths as input

When accepting file system paths as input, we should use read with the -e option, as this allows the user to use tab to complete file- and directory names.

read -e inputPath

However, this is not quite enough, since the user might also enter magic variables, such as the $USER variable, which will link to the users home directory. Simply replacing these special cases with the expected value is not always enough.

We also got the curious case of the tilde (~) character, which can be used as a "shortcut" to the users home directory. However, it can also be used to obtain the home directory of other users.

Because of this, we should take care to parse user supplied paths Properly.

See also: Using tilde in sh scripts

Comments