内联操作后bash全局变量未更改

时间:2015-05-02 05:42:09

标签: bash

我有一个以逗号分隔的字符串变量,我需要删除来自标准输入的值,这些值来自文件。当我完成脚本时,不会从变量中删除值,但您可以告诉它们在do循环中被删除。如何更新操作的do循环中的全局var?

#!/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

所以你会注意到循环从字符串中删除了值,但当它退出循环时,变量在进入循环之前仍然是原始值。

1 个答案:

答案 0 :(得分:2)

下面,

cat /tmp/fileFeed.txt | while read word; do
   ....
done

while循环在子shell中执行。所以没有任何变量'值将在循环外可用。将其更改为:

while read word; do
   ....
done < /tmp/fileFeed.txt

您可能也有兴趣阅读useless use of cat