Reputation: 3422
How do I read user input into a variable in Bash?
fullname=""
# Now, read user input into the variable `fullname`.
Upvotes: 252
Views: 416619
Reputation: 75588
Use read -p
:
# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user
If you like to get the user's confirmation:
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
You should also quote your variables to prevent filename expansion and word splitting with spaces:
# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"
Upvotes: 461
Reputation: 27271
printf "%s" "Enter fullname: "
read fullname
This is the most portable way to read with prompt. Methods such as read -p
and echo -n
are more likely to fail depending on the shell.
Upvotes: 17
Reputation: 4877
https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html
One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split into words as described above in Word Splitting, and the first word is assigned to the first name, the second word to the second name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name.
echo "bash is awesome." | (read var1 var2; echo -e "Var1: $var1 \nVar2: $var2")
bash
will be var1
is awesome
will be var2
echo -e
enable interpretation of backslash escapes from ubuntu manual.
so the full code can be:
echo -n "Enter Fullname: "
read fullname
echo "your full name is $fullname."
echo -n "test type more than 2 word: "
read var1 var2; echo -e
read var1 var2; echo -e "Var1: $var1 \nVar2: $var2")
Upvotes: 4
Reputation: 10673
Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1
Upvotes: 6
Reputation: 369
Yep, you'll want to do something like this:
echo -n "Enter Fullname: "
read fullname
Another option would be to have them supply this information on the command line. Getopts is your best bet there.
Using getopts in bash shell script to get long and short command line options
Upvotes: 25