简体   繁体   中英

bash script interpreting awk correctly

I have a for loop script that needs to log into hosts and get their hostname and the value of eth0 interface. Im using the code below, but the awk command is not being read correctly when running it on a bash script

    #!/bin/bash

for i in `cat test.txt`;

do

store_number=$(ssh -q -A -o userknownhostsfile=/dev/null -o stricthostkeychecking=no -o batchmode=yes -o connecttimeout=5 "$i" "hostname | cut -c4-7");

eth0_ip=$(ssh -q -A -o userknownhostsfile=/dev/null -o stricthostkeychecking=no -o batchmode=yes -o connecttimeout=5 "$i" "sudo ifconfig eth0 | awk 'FNR==2 {print $2}'");

output="${store_number}: ${eth0_ip}"; echo $output >> /home/eth0status.txt;

done

The output is as follow:

0021: inet addr:10.1.10.62 Bcast:10.1.10.255 Mask:255.255.255.0

0022: inet addr:10.0.1.74 Bcast:10.0.1.255 Mask:255.255.255.0

0023: inet addr:172.16.16.103 Bcast:172.16.16.255 Mask:255.255.255.0

I need the output to be something like:

0021: addr:10.1.10.62 

0022: addr:10.0.1.74

0023: addr:172.16.16.103

Thanks for your help

Quoting is a hard problem. When you write:

eth0_ip=$(ssh ... "$i" "sudo ifconfig eth0 | awk 'FNR==2 {print $2}'");

The internal single quotes '' do nothing to prevent expansion of $2 . The shell sees $2 in double quotes. It will perform variable expansion, and it's highly likely your second argument ( $2 for the script) is unset. Test it out:

$ echo "sudo ifconfig eth0 | awk 'FNR==2 {print $2}'"
sudo ifconfig eth0 | awk 'FNR==2 {print }'

Either escape $ , or use single quotes outside, or as others have recommended, use awk outside the SSH command.

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