1

below ism y code

if [ ip add show tun0 2>/dev/null ] ; then
    export http_proxy="http://127.0.0.1:2123"
fi

But when i do echo after conencting

echo $http_proxy

it is not displaying. can advice?

shalene
  • 15
  • 3
  • 1
    First: when troubleshooting, remove the `2>/dev/null` so you can see the error message. Second: if the goal is to test the success/failure of `ip ...` as a command, remove the `[ ]` (see [this question](https://stackoverflow.com/questions/49849957/bash-conditional-based-on-exit-code-of-command)). – Gordon Davisson May 13 '22 at 04:28
  • You are not executing the command `ip`, you are executing the command `[`. The first word after the `if` is the command to be executed for testing the condition. This is described in the section _Compound Commands_ in the bash man-page. – user1934428 May 13 '22 at 05:52

1 Answers1

0

@GordonDavisson suggested:

if ip add show tun0 2>/dev/null
then
   export http_proxy='http://127.0.0.1:2123'
fi

but you could also write it like this:

ip add show tun0 2>/dev/null && export http_proxy='http://127.0.0.1:2123'

ip will print stuff on stdout when successful, so maybe you want to do >& /dev/null? Instead of throwing all the data away, consider storing it in a variable, then you can always add a verbose flag to your program at some later point to print the content of that variable if you need to debug it.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • i tried but it not showing. i connect vpn it use tun0. when i echo it not showing the value – shalene May 13 '22 at 05:20
  • What is not showing? If you get no output, then it would mean that you don't have the tun0 interface. Or you have a different error, so run the program without the 2>/dev/null redirect and tell us what you get. – Allan Wind May 13 '22 at 05:31
  • was my mistake, i need to relog in to shell. thank you guys for the great help – shalene May 13 '22 at 05:41
  • Where do you display the var? Outside the script that adds the interface? If yes, then the outer bash ignores the definition of the scrip (sub-shell). – Wiimm May 13 '22 at 08:24