Bash:在case语句中更新变量

时间:2019-03-20 11:44:41

标签: bash variables scope case

上下文

我目前正在尝试编写一个base脚本,在其中使用case语句。 我在该case语句上方声明了一个变量,并在某些情况下尝试对其进行更新。

由于未知原因,赋值在case语句中起作用,但是一旦我退出case语句,变量值就不一样了。 有人可以给我一个提示吗?

代码

这是我的脚本,其中一些简化的部分不属于我的问题:

#!/bin/bash
count=0
valuetowatch=false

#read a file from line 2 to 6 and parse line by line
awk 'NR >= 2 && NR <= 6' /my/file/path.txt | while read -r line; do
    count=$((count+1))
    case $count in
        [15])
            if [ something ]
            then
                valuetowatch=true
                echo $valuetowatch #<-- works here (true)
            fi
            ;;
        [24])
            #The length of STRING is greater than zero.
            if [ something ]
            then
                valuetowatch=true
                echo $valuetowatch #<-- works here (true)
            fi
            ;;
    esac
done
echo $valuetowatch #<-- gives me the initial value... (false)

谢谢!

编辑:解决方案

while循环在另一个子shell中运行,因此更新的变量不会返回到主子shell中。解决方法如下:

#!/bin/bash
count=0
valuetowatch=false

#read a file from line 2 to 6 and parse line by line
$lines=$(awk 'NR >= 2 && NR <= 6' /my/file/path.txt)
while read -r line; do
    count=$((count+1))
    case $count in
        [15])
            if [ something ]
            then
                valuetowatch=true
                echo $valuetowatch #<-- works here (true)
            fi
            ;;
        [24])
            #The length of STRING is greater than zero.
            if [ something ]
            then
                valuetowatch=true
                echo $valuetowatch #<-- works here (true)
            fi
            ;;
    esac
done <<< "$lines"
echo $valuetowatch #<-- it works ! (true)

0 个答案:

没有答案
相关问题