Bash is a shell for Linux and Unix operating systems. But bash also provides some basic programming environment acting like a Programming language. System administrators generally develops simple scripts and apps with bash and reads some input from shell interactively. In this tutorial we will look ho to read input from interactive bash console or terminal.
By Using Read
One way to get input from shell prompt is read. We use read and and question text to show and end of the line the variable name. This is the simplest form of getting an
no prompt from user.
$ read -p "Do you accept license?(y/n)" ans Do you accept licence?(y/n)n $ echo $ans n
The other way with read is following printing text before and reading input after text with read.
$ echo "Do you accept license?(y/n)";read ans Do you accept licence?(y/n) y
By Using Select
Another way to read input from bash shell is using conditional statement
select . This will read from console and set provided value to the
ans bash variable.
echo "Do you accept license?" select ans in "Yes" "No"; do case $ans in Yes ) break;; No ) break;; esac done
By Using Whiptail
There is a library developed with ncurses which provides simple GUI for bash. Whiptail is used to read user input with a more beautiful way by providing graphical interface. In this example we simply provide
--yesno to the whiptail and it shows these predefined options. The result will be returned as
No which is evaluated in a
if conditional statement.
$ if whiptail --yesno "Do you accept license?" 20 60 ;then echo Yes; else echo No; fi Yes $
How Prompt for Input in Bash Infografic