How Prompt for Input in Bash – POFTUT

How Prompt for Input in Bash

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 yes , no prompt from user.

$ read -p "Do you accept license?(y/n)" ans 
Do you accept licence?(y/n)n 
$ echo $ans 

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) 

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;; 

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 Yes or 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                        
By Using Whiptail
By Using Whiptail


LEARN MORE  How To Run Parallel Jobs/Process/Programs in Bash

How Prompt for Input in Bash Infografic

How Prompt for Input in Bash Infografic
How Prompt for Input in Bash Infografic


Leave a Comment