0

I have a script to add IPv6s. But I need to figure out how to assign the output of the command to a variable and then use it further in the code. This is what I have

 ret=$(/sbin/ifconfig eth0 inet6 add $IPV6PROXYADD)
 if [ "$ret" ];
 then
  returnflag="error"
  echo "$ret" >> "/root/mypath/ipv6/ipadderror.log"
 fi

But the script would output the result to screen instead of assigning it to the variable. What am I doing wrong here?

endeavour
  • 576
  • 4
  • 15

2 Answers2

1

You probably want something more like this.

/sbin/ifconfig eth0 inet6 add $IPV6PROXYADD > /root/mypath/ipv6/ipadderror.log 2>&1
if [ $? -ne 0 ] ;
then
  returnflag="error"
fi

Even in the success case, your log will contain both stdout and stderr of the ifconfig command. You probably want to exit in the error case as well, perhaps with a non-zero exit status, a more standard way of indicating error than some string flag.

Rumbleweed
  • 370
  • 1
  • 9
  • The reason I wanted to use a variable was because the actual script uses the code `echo "$datetime: $IPV6PROXYADD -> $ret"`. Not sure how to implement this with this method – endeavour Feb 03 '16 at 17:57
  • @endeavour Assign your variable after the ifconfig command like this: **ret=\`cat /root/mypath/ipv6/ipadderror.log\`** – Rumbleweed Feb 04 '16 at 14:34
  • See also [http://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script] – Rumbleweed Feb 04 '16 at 14:39
1

I decided to add another answer rather than modify my original. This approach keeps most of your original code (though it is not my style :-)

ret=$( /sbin/ifconfig eth0 inet6 add $IPV6PROXYADD 2>&1 )
if [ $? -ne 0 ];
then
  returnflag="error"
  echo "$ret" >> "/root/mypath/ipv6/ipadderror.log"
fi

I kept the return code check $? rather than looking at the content of variable ret.

Rumbleweed
  • 370
  • 1
  • 9
  • The reason for this approach is because these lines are in a loop which runs for about 1000 iterations. And once the loop is complete I want to check how many failed (if any). On success the script deletes the file from which $IPV6PROXYADD is read, runs many other commands and on failure it informs dev to take a look manually. These actions need to be taken only after the completion of the loop. Can you suggest a better way to do this. – endeavour Feb 05 '16 at 05:20