#!/bin/sh

test()
{
RetVal=0

cat 1.log | while read line
do
if[ "$line" == "2" ]
then
RetVal=1
fi
done

return $RetVal
}

 

很容易写出上述代码,上述代码返回值始终为0。虽然执行了RetVal=1这条语句,但是一出while循环,变量值又变成0了。

这是因为管道是在子shell中执行的,子shell中的变量对于子shell之外的代码块来说, 是不可见的. 当然, 父进程也不能访问

这些变量, 父进程指的是产生这个子shell的shell. 事实上, 这些变量都是局部变量。

 

#正确做法
test()
{
RetVal=0

while read line
do
if[ "$line" == "2" ]
then
RetVal=1
fi
done < 1.log

return $RetVal
}