在bash脚本中获取局部变量值

时间:2014-06-04 19:39:26

标签: bash

我是bash脚本尝试读取文件的新手,如果匹配的字符串存在,我会在变量值中添加一些东西。我猜它正在考虑它作为局部变量,我无法在后面的代码部分使用该值。 如何在外面获得这个价值?请给我所有可能的方法

if(...)
then
    ..........
elif (file exists)
then
    cat file | while read line
    do
    if [ "$line" = "something" ]
    then 
        value="correct"
    fi
    done
elif()
.........
fi
echo "value is $value"

输出: 价值是

2 个答案:

答案 0 :(得分:2)

while循环正在一个单独的进程中运行,因为它位于管道的右侧,因此无法修改其父环境。改为使用重定向:

 while read line
 do
    # ...
 done < file

答案 1 :(得分:1)

只需先在代码中定义value,例如在第一行:

value=""
if (file exists)
then
    cat file | while read line
    do
    if [ "$line" = "something" ]
    then 
        value="correct"
    fi
    done
elif()
.........
fi
echo "value is $value"