我有一个逗号划界字符串变量,我需要删除来自文件来自文件的标准输入的值。当我完成脚本时,该值不会从变量中删除,但是您可以说它们已在DO循环中删除。如何更新操作DO循环内的全局变量?
#!/bin/bash
varFoo="text1,text2,obit,poodle,text2,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush"
echo text2 > /tmp/fileFeed.txt
echo circuit >> /tmp/fileFeed.txt
echo rush >> /tmp/fileFeed.txt
cat /tmp/fileFeed.txt | while read word; do
removeWord=${varFoo//$word,/}
removeWord=${removeWord//,$word/}
echo ========== transaction seperator ==========
echo word=$word
echo removeWord=$removeWord
varFoo=$removeWord
done
echo ^^^^^^^^^^^exiting work loop and heading to the end ^^^^^^^^^^^
echo FINAL varFoo = $varFoo
exit $?
输出为
========== transaction seperator ==========
word=text2
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush
========== transaction seperator ==========
word=circuit
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,bum,rush
========== transaction seperator ==========
word=rush
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,bum
^^^^^^^^^^^exiting work loop and heading to the end ^^^^^^^^^^^
FINAL varFoo = text1,text2,obit,poodle,text2,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush
因此,您会注意到循环从字符串中删除值,但是当它退出循环时,变量仍处于原始值之前。
在这里,
cat /tmp/fileFeed.txt | while read word; do
....
done
while循环在子壳中被执行。因此,变量的值都不可在循环之外可用。将其更改为:
while read word; do
....
done < /tmp/fileFeed.txt
您可能也有兴趣阅读猫的无用使用。