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?

ADVERTISEMENTS

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 SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig 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 jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
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>, <code>...</code> and <kbd>...</kbd> for code samples.