SuperheroSmith
SuperheroSmith

Reputation: 3

How to use a variable in a command that's creating another variable

I created my basic variable from a read command (I've done this manually and using a script):

read NAME

I then want to use that NAME variable to search a file and create another variable:

STUDENT=$(grep $NAME <students.dat | awk -F: '/$NAME/ {print $1}')

If I run the command manually with an actual name from that students.dat file (and not $NAME), it executes and displays what I want. However, when I run this command (manually or from the script using $NAME), it returns blank, and I'm not sure why.

Upvotes: 0

Views: 44

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133760

@user1615415: Try:

cat script.ksh
echo "Enter name.."
read NAME
STUDENT=$(awk -vname="$NAME" -F: '($0 ~ name){print $3}' student.dat)

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 362097

Shell variables aren't interpolated in single quotes, only double quotes.

STUDENT=$(grep $NAME <students.dat | awk -F: "/$NAME/ {print \$1}")

$1 needs to be escaped to ensure it's not expanded by the shell, but by awk.

Upvotes: 1

Related Questions