Home > other >  bash command fails when used with variables
bash command fails when used with variables

Time:08-01

I use a Linux (Ubuntu) bash. When I ping an address dirrectly - all work fine. But when I use it with a variable that gets it's value from calculation - it fails.

what am i doing wrong?

network=`ip r | grep default | awk '{print $3;}'`
echo $network   # prints: 10.0.0.138
ping $network   # prints: ping: 10.0.0.138: Name or service not known (ERROR???)
ping 10.0.0.138 # prints: PING 10.0.0.138 (10.0.0.138) 56(84) bytes of data. (OK)

CodePudding user response:

it's becaues the result is colored... ipis aliased to ip -c

so - this had solved the issue:

 network=`/usr/bin/ip r | grep default | awk '{print $3;}'`

CodePudding user response:

That sequence should work OK at the command line (it'd be interesting to see a screenshot). However you can lose the grep and use a more rigorous awk script:

defaultgw=$(ip r | awk '{if ($1=="default") print $3}')

Then just send a single echo-request without any name resolution:

ping -n -c 1 $defaultgw
  • Related