0

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)
5
  • 1
    Use set -x to find out what is stored in $network. Commented Aug 1, 2022 at 8:36
  • + set -x '10.0.0.138' Commented Aug 1, 2022 at 8:39
  • with quotes (???) - that's probably the problem Commented Aug 1, 2022 at 8:40
  • 1
    There's probably some sort of nonprinting character in $network causing trouble. Rather than echo $network, try printf %s "$network" | xxd and see what that shows. Commented Aug 1, 2022 at 8:57
  • 00000000: 1b5b 3335 6d31 302e 302e 302e 3133 38 .[35m10.0.0.138 Commented Aug 1, 2022 at 9:00

2 Answers 2

2

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;}'`
Sign up to request clarification or add additional context in comments.

Comments

-1

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

2 Comments

dudu@dudu-pc:~$ defaultgw=$(ip r | awk '{if ($1=="default") print $3}') dudu@dudu-pc:~$ ping -n -c 1 $defaultgw ping: 10.0.0.138: Name or service not known
it should, but it doesn't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.