下面的示例取自William的Linux命令行。它是一个shell脚本,它从/etc/passwd文件中收集用户信息。完成此操作的特定用户从stdin读取。
我的问题是关于第7行中使用的“这里字符串”,只是为了解决问题,我尝试使用重定向操作符,但没有起作用。为什么?
PS:我在C++中有一些背景,所以我希望字符串file_info充当一个字符串流。
1 #!/bin/bash
2 # read-ifs: read fields from a file
3 FILE=/etc/passwd
4 read -p "Enter a username > " user_name
5 file_info="$(grep "^$user_name:" $FILE)"
6 if [ -n "$file_info" ]; then
7 IFS=":" read user pw uid gid name home shell <<< "$file_info"
8 echo "User = '$user'"
9 echo "UID = '$uid'"
10 echo "GID = '$gid'"
11 echo "Full Name = '$name'"
12 echo "Home Dir. = '$home'"
13 echo "Shell = '$shell'"
14 else
15 echo "No such user '$user_name'" >&2
16 exit 1
17 fi发布于 2019-12-20 02:46:28
如果你做这样的事
grep "^$user_name:" $FILE | IFS=":" read user pw uid gid name home shell
echo "User = '$user'"管道的右侧( read命令)在它自己的子subshell进程中运行,它设置的变量在结束时消失,所以echo只显示空字符串。
但你可以做这样的事
grep "^$user_name:" $FILE | ( IFS=":" read user pw uid gid name home shell
echo "User = '$user'" )在本例中,整个( . )部件在同一个子subshell中运行,并且变量可用于echo调用。
https://askubuntu.com/questions/1197400
复制相似问题