如何将用户输入读入 Bash 中的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18544359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:08:22  来源:igfitidea点击:

How to read user input into a variable in Bash?

bashshell

提问by Geofferey

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.

我正在尝试创建一个脚本,以简化在 iOS 设备上创建新用户的过程。以下是分解的步骤。

# 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?

如您所见,某些字段需要输入。如何在脚本中请求输入变量?

回答by konsolebox

Use read -p:

使用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"

回答by jjulien

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.

另一种选择是让他们在命令行上提供此信息。Getopts 是您最好的选择。

Using getopts in bash shell script to get long and short command line options

在 bash shell 脚本中使用 getopts 获取长短命令行选项

回答by Aleks-Daniel Jakimenko-A.

Also you can try zenity!

你也可以试试zenity

user=$(zenity --entry --text 'Please enter the username:') || exit 1

回答by Nishant Ingle

Try this

尝试这个

#/bin/bash

read -p "Enter a word: " word
echo "You entered $word"