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


83

我正在尝试创建一个脚本,以简化在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

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

Answers:


171

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

7
您可以使用${confirm^^} == 'YES'
Aleks-Daniel Jakimenko-A。

1
@ Aleks-DanielJakimenko这是其他人常用的方法,但仅与4.0+兼容。
konsolebox

附带说明:exit 1表示错误退出。
蒂莫



1

试试这个

#/bin/bash

read -p "Enter a word: " word
echo "You entered $word"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.