≡ Menu

How do you take a single line of input from the user in a shell script?

Q. I need to write a shell script to prompt databasename, username and password from the user. How do I take a single line of input from the user in a shell script?

A. You need to use read command in a shell script to read single line of input frm the user in a shell.

One line is read from the standard input (keyboard), or from file descriptor FD if the -u option is supplied, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with leftover words assigned to the last NAME.


read {variable-name}
read -p {‘Prompt text’} {variable-name}

Read single line of input from the user and store to variable called dbname:
read dbname
read -p 'Enter Database name : ' dbname

To display variable value, enter:
echo $dbname

Sample shell script

read -p 'Enter mysql database name : ' dbname
read -p 'Enter username : ' dbuname
read -s -p 'Enter password : ' dbpass
mysql -uroot -p'Password'<<EOFMYSQL
GRANT ALL ON $dbname.* TO $dbuname@localhost IDENTIFIED BY "$dbpass";
Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 4 comments… add one }
  • sujit November 13, 2007, 6:38 am

    thanks. this thing worked for my java apps.

  • Charanjit Singh December 18, 2009, 11:11 am

    Hi Vivek
    Thanks for the tips this helps me lot.

  • Ashish July 27, 2011, 8:50 am


  • Boopathy July 13, 2014, 7:55 am

    Hi , If we need to get amny words as a input from console . What is the option ?
    For example ..
    read -p ” Enter your Message” message

    user input is here ..
    Hr meeting today at 11.30 PM . Please gather.

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: