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

问题描述 投票:0回答:6

如何在 Bash 中将用户输入读取到变量中?

fullname=""
# Now, read user input into the variable `fullname`.
bash shell input
6个回答
407
投票

使用

read -p

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

如果您想得到用户的确认:

read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

您还应该引用变量以防止路径名扩展和用空格进行单词分割:

# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

23
投票

是的,你会想做这样的事情:

echo -n "Enter Fullname: " 
read fullname

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

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


19
投票

试试这个

#/bin/bash

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

12
投票

最大程度可移植(bash、zsh...):

printf "%s" "Enter fullname: "
read fullname

这是最便携的提示阅读方式。诸如

read -p
echo -n
之类的方法更有可能失败,具体取决于 shell。


5
投票

你也可以尝试zenity

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

4
投票

https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html

从标准输入或文件描述符读取一行 fd 作为 -u 选项的参数提供,拆分为单词 上面在分词中描述过,第一个词被分配给 第一个名字,第二个单词到第二个名字,依此类推。如果 单词比名字还多,剩下的单词和它们的 中间分隔符被分配给姓氏。

echo "bash is awesome." | (read var1 var2; echo -e "Var1: $var1 \nVar2: $var2")

bash
将是 var1
is awesome
将是 var2
echo -e
启用对 ubuntu 手册中的反斜杠转义的解释。


所以完整的代码可以是:

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")
© www.soinside.com 2019 - 2024. All rights reserved.