Rishi Reddy
Rishi Reddy

Reputation: 39

Not able to store output of awk command into a variable

I am trying to do the following :

#!/bin/bash

echo "Enter Receiver HostNames (comma separated hostname list of receivers):"
read receiverIpList

receiver1=`$receiverIpList|awk -F, '{print $1}'`

echo $receiver1

when I run the script I am getting below error.

./test1.sh
Enter Receiver IP Addresses (comma separated IP list of receivers):
linux1,linux2
./test1.sh: line 6: linux1,linux2: command not found

Could someone please tell me what's wrong in the script??

Upvotes: 0

Views: 179

Answers (1)

Ed Morton
Ed Morton

Reputation: 203512

The syntax you're trying to use would be:

receiver1=`echo "$receiverIpList"|awk -F, '{print $1}'`

but your approach is wrong. Just read the input directly into a bash array and use that:

$ cat tst.sh
echo "Enter Receiver HostNames (comma separated hostname list of receivers):"
IFS=, read -r -a receiverIpList
for i in "${!receiverIpList[@]}"; do
  printf '%s\t%s\n' "$i" "${receiverIpList[$i]}"
done

$ ./tst.sh
Enter Receiver HostNames (comma separated hostname list of receivers):
linux1,linux2
0   linux1
1   linux2

Even if you didn't want to do that for some reason, you still shouldn't use awk, just use bash substitution or similar, e.g.:

$ foo='linux1,linux2'; bar="${foo%%,*}"; echo "$bar"
linux1

Be careful of your spelling btw as in your posted code sample you're sometimes spelling receiver correctly (receiver) and sometimes incorrectly (reciever) - that will probably bite you at some point when you're trying to use a variable name but actually using a different one instead due to flipping the ei. The question has now been fixed to avoid this problem, I see.

Upvotes: 2

Related Questions