简体   繁体   English

无法从Bash中的命令填充变量

[英]Can't populate variable from command in Bash

I'm new to bash scripting, and I'm working on a script where the user enters a username and gets a list of the associated information from /etc/passwd. 我是bash脚本的新手,我正在研究一个脚本,其中用户输入用户名并从/ etc / passwd获取相关信息的列表。 Unfortunately, I seem to be having trouble populating a variable from a command. 不幸的是,我似乎无法从命令中填充变量。 The error message I'm getting suggests the if statement isn't being entered into, but I'm not sure why. 我收到的错误消息提示未输入if语句,但是我不确定为什么。

The script currently looks like this: 该脚本当前如下所示:

#!/bin/bash

#readifs

FILE=/etc/passwd

read -p "Enter a username > " user_name

file_info=$(grep "^$user_name:" $FILE)

if [ -n "$file_info" ]; then
     IFS=":" read user pw uid gid name home shell <<< "$file_info"
     echo "User = '$user'"
     echo "UID = '$UID'"
     echo "GID = '$GID'"
     echo "Full Name = '$name'"
     echo "Shell = '$shell'"
else
     echo "No such user '$user_name'" > &2
     exit 1
fi

When I run it, using a valid username, I get the following two lines: 当我使用有效的用户名运行它时,得到以下两行:

readifs.sh: line 20: syntax error near unexpected token `&'
readifs.sh: line 20: `  echo "No such user '$user_name'" > &2'

I'm pretty sure I'm missing something obvious, or doing something bash doesn't allow but I'm too new to catch. 我很确定我缺少明显的东西,或者不允许执行bash动作,但是我太新了,无法捕捉。 Can anyone point out and correct the error in my script? 谁能指出并更正我脚本中的错误?

Thank you to Charles Duffy for all the great feedback on not just this script, but bash scripting and Stack Overflow in general. 感谢Charles Duffy不仅对这个脚本,而且对bash脚本和一般的Stack Overflow都给予了很好的反馈。

I was able to fix the script as I wanted. 我能够根据需要修复脚本。 I removed the ^ and : from the file_info line, which was stopping the grep command from finding the line I wanted. 我从file_info行中删除了^和:,这使grep命令无法找到我想要的行。 I also renamed $UID and $GID to use lower case letters, and removed the space in "> &2". 我还重命名了$ UID和$ GID以使用小写字母,并删除了“>&2”中的空格。

Thank you again for your assistance. 再次感谢您的协助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM