How to read user input into a variable in Bash?

2020-01-27 00:28发布

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 shell
3条回答
一纸荒年 Trace。
2楼-- · 2020-01-27 00:55

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"
查看更多
该账号已被封号
3楼-- · 2020-01-27 01:00

Also you can try zenity !

user=$(zenity --entry --text 'Please enter the username:') || exit 1
查看更多
smile是对你的礼貌
4楼-- · 2020-01-27 01:09

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

查看更多
登录 后发表回答