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.

Syntax:

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
OR
read -p 'Enter Database name : ' dbname

To display variable value, enter:
echo $dbname

Sample shell script

#!/bin/bash
read -p 'Enter mysql database name : ' dbname
read -p 'Enter username : ' dbuname
read -s -p 'Enter password : ' dbpass
mysql -uroot -p'Password'<<EOFMYSQL
CREATE DATABASE $dbname;
GRANT ALL ON $dbname.* TO $dbuname@localhost IDENTIFIED BY "$dbpass";
EOFMYSQL

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • sujit Nov 13, 2007 @ 6:38

    thanks. this thing worked for my java apps.

  • Charanjit Singh Dec 18, 2009 @ 11:11

    Hi Vivek
    Thanks for the tips this helps me lot.

  • Ashish Jul 27, 2011 @ 8:50

    thanks

  • Boopathy Jul 13, 2014 @ 7:55

    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.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum