简体   繁体   中英

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. 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.

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. 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.

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. I also renamed $UID and $GID to use lower case letters, and removed the space in "> &2".

Thank you again for your assistance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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