How to read user input into a variable in Bash?
BashShellBash Problem Overview
I'm trying to create a script that simplifies the process of creating a new user on an iOS device. Here are the steps broken down.
fullname="USER INPUT"
user="USER INPUT"
group=$user
uid=1000
gid=1000
home=/var/$user
echo "$group:*:$gid:$user" >> /private/etc/group
echo "$user::$uid:$gid::0:0:$fullname:$home:/bin/sh" >> /private/etc/master.passwd
passwd $user
mkdir $home
chown $user:$group $home
As you can see some fields require input. How can I request input for a variable in script?
Bash Solutions
Solution 1 - Bash
Use read -p
:
# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user
If you like to confirm:
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
You should also quote your variables to prevent pathname expansion and word splitting with spaces:
# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"
Solution 2 - Bash
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.
Solution 3 - Bash
Try this
#/bin/bash
read -p "Enter a word: " word
echo "You entered $word"
Solution 4 - Bash
Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1
Solution 5 - Bash
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")