0
p=sudo npm config get proxy;
echo "$p";
if [ -z $p ] 
 then
  echo "delete";
  sudo npm config delete proxy http://xxx.xx.xxx.xxx:8085
 else 
 echo "set";
  sudo npm config set proxy http://xxx.xx.xxx.xxx:8085
fi

I have tried this but didn't get result

1 Answers1

4

There wasn't too much wrong with your script:

  1. setting a variable to the output of a command (i.e. Command Substitution) needs $() around the command. I am deliberately ignoring the existence of obsolete backticks for the same purpose, they are broken in several ways.

  2. quote your variables when you use them.

    e.g. if [ -z $p ] without quotes is guaranteed to be a syntax error if $p is actually empty because -z requires an argument. if [ -z "$p" ] will never cause an error because even an empty string is an argument.

Here's a minimally fixed version (also with superfluous semicolons removed):

p="$(sudo npm config get proxy)"
echo "$p"
if [ -z "$p" ] ; then
  echo "delete"
  sudo npm config delete proxy http://xxx.xx.xxx.xxx:8085
else 
  echo "set"
  sudo npm config set proxy http://xxx.xx.xxx.xxx:8085
fi
cas
  • 78,579
  • BTW, the -z probably needs to be a -n. The way it's written now, it attempts to delete the proxy setting if "$p" is empty (i.e. no proxy has been configured) which effectively does nothing, and sets a proxy if one is already set. But that's what I meant by "minimally fixed" - I fixed the obvious errors, without any consideration of whether your script actually does what you want/expect or not....I'll leave that up to you. – cas Jan 23 '18 at 14:10
  • Mind expanding on your comment on why backticks are "broken in several ways"? – Foxocube Jan 23 '18 at 16:01
  • quoting issues. you can't nest backticks. difficult to distinguish from single-quotes. general ugliness. some (unverified) reports of demonic manifestations. see, e.g., https://unix.stackexchange.com/questions/126927/have-backticks-i-e-cmd-in-sh-shells-been-deprecated and https://mywiki.wooledge.org/BashFAQ/082 and http://wiki.bash-hackers.org/syntax/expansion/cmdsubst. backticks still work (as well...badly...as they ever did) but don't use them. backticks are evil, and they will cause your hamster to spontaneously explode. – cas Jan 23 '18 at 16:14
  • But ... I don't have a hamster. Now I'm even more worried. – Foxocube Jan 23 '18 at 16:50
  • i accidentally deleted the chilling end to that sentence - "even if you don't have a hamster". – cas Jan 23 '18 at 16:58
  • No it doesnot solve my problem , it is going in if condition only , not matching 'null" @cas – yogesh agrawal Jan 24 '18 at 04:28
  • i want to toggle proxy, if set then delete or vice versa. – yogesh agrawal Jan 24 '18 at 04:29
  • if npm config get proxy returns the string null rather than an empty string, then test for [ "$p" == 'null' ] rather than [ -z "$p" ] - is that somehow not completely obvious? – cas Jan 24 '18 at 05:00