Bash variable scope -


please explain me why last "echo" statement blank? expect incremented in while loop value of 1:

#!/bin/bash output="name1 ip ip status" # output of command multi line output  if [ -z "$output" ]         echo "status warn: no messages smcli"         exit $state_warning else         echo "$output"|while read name ip1 ip2 status                         if [ "$status" != "optimal" ]                                         echo "crit: $name - $status"                         echo $((++xcode))                 else                         echo "ok: $name - $status"                 fi         done fi  echo $xcode 

i've tried using following statement instead of ++xcode method

xcode=`expr $xcode + 1` 

and wont print outside of while statement. think i'm missing variable scope here ol' man page isnt showing me.

because you're piping while loop, sub shell created run while loop. child process has it's own copy of environment , can't pass variables parent (as in unix process).

therefore you'll need restructure you're not piping loop. alternatively run in function example , echo value want returned sub process.

http://tldp.org/ldp/abs/html/subshells.html#subshell


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -