Rob
Rob

Reputation: 312

Bash - Using variable inside command not working

I am not sure why this does not work. (I researched it and found nothing.)

I'm trying to ping an IP and get the result. Then get the avg time and packet loss from the result

PING=$(ping -c $AMOUNT -s $SIZE $IP)
AVG_TIME=$($PING | tail -1 | awk '{print $4}' | cut -d '/' -f 2)
PACKET_LOSS=$($PING | grep -oP '\d+(?=% packet loss)')

Error:

PING: command not found

It works if I put the PING command inside each of the other commands, but that means it will ping once for each not get the values from the one ping result.

I have been over it many times, but I think I have missed something here.

Upvotes: 0

Views: 184

Answers (1)

P.P
P.P

Reputation: 121387

You want to get the output from the ping command. So change it to:

AVG_TIME=$(echo "$PING" | tail -1 | awk '{print $4}' | cut -d '/' -f 2)
PACKET_LOSS=$(echo "$PING" | grep -oP '\d+(?=% packet loss)')

Notice the echo command above.

With the current code, it's trying to execute the output of your first command which is not what you want.

Upvotes: 3

Related Questions