bash - Value of an out of cycle defined variable disapperas out of a cycle -
this question has answer here:
cd /var/log grep "ufw block" syslog | cut -d ' ' -f 13 | sort -u > pippo.txt k=0 i=1 ip="" cat pippo.txt | while read line (( k += )) ip=${line:4} echo "ip " $ip" added list." echo -n "k=" echo $k ufw deny $ip > /dev/null done echo -n "processed , added " echo "$k" echo " ip via ufw firewall."
why k variabale keeps contenent into cicle , loose it? during while - done cicle echo prints correct k value, out of cicle, after done line, k printed zero.
it because subshell created pipe |
.
the subshell copies current environment , runs new code in it.
cd /var/log grep "ufw block" syslog | cut -d ' ' -f 13 | sort -u > pippo.txt k=0 i=1 ip="" # pipe creates environment of own k=0, i=1 , ip="" cat pippo.txt | while read line # subshell increments own version of k (( k += )) ip=${line:4} echo "ip " $ip" added list." echo -n "k=" echo $k ufw deny $ip > /dev/null done # subhell no longer exists echo -n "processed , added " # prior environment prints version of k 0 echo "$k" echo " ip via ufw firewall."
you fix removing pipe , doing read in file.
while read line (( k += )) ip=${line:4} echo "ip " $ip" added list." echo -n "k=" echo $k ufw deny $ip > /dev/null done < pippo.txt
this should give same effect leave in same shell
mini example
you can see effect of subshell behaviour running following one liner
k=0; echo $( (( k++ )); echo $k ); echo $k
this prints out 1
0
might expect print 1
1
. works off same principle of subshells $( )
subshell inherited environment.
Comments
Post a Comment