bash脚本变量的作用域问题 [英] Bash Script Variable Scope Issue
问题描述
username="hello"
password="3333"
function login {
# 1 - Username
# 2 - Password
match=0
cat LoginsMaintMenu.txt | while read line; do
x=`echo $line | awk '{print $1}'`
y=`echo $line | awk '{print $2}'`
if [ "${x}" == "${1}" ] && [ "${y}" == "${2}" ]; then
echo "match"
match=1
echo $match
break
fi
done
echo $match
return $match
}
echo $username $password
login ${username} ${password}
if [ $? -eq 0 ]; then
echo "FAIL"
else
echo "success"
fi
输出:
hello 3333
match
1
0
FAIL
问题:
我不明白为什么它呼应不及格。在匹配变量被设置为1,while循环中,但由于某些原因,一旦我出了while循环,它仍然认为它是从它的声明初始零的。
THE PROBLEM: I don't understand why it is echoing "fail". the "match" variable gets set to 1 inside the while loop, but for some reason once I am out of the while loop it still thinks it is the initial zero from its declaration.
我曾尝试做很多不同的事情,因此,如果有人可以给我一些具体的尝试会是伟大的!
I have tried doing a lot of different things, so if someone could give me something concrete to try that'd be great!
感谢
推荐答案
究其原因,这是不工作实际上是的 UUOC 。在bash中,管道的右侧是一个子shell的冲了进去。一个子壳内部设置的任何变量将不会在父shell进行设置。为了解决这个问题,可以使用,而不是一个管道重定向:
The reason that this is not working is actually the UUOC. In bash, the right side of a pipeline is ran inside of a sub-shell. Any variables set inside of a sub shell will not be set in the parent shell. To fix this, use redirection instead of a pipeline:
username="hello"
password="3333"
function login {
# 1 - Username
# 2 - Password
match=0
while read x y _; do
if [ "${x}" == "${1}" ] && [ "${y}" == "${2}" ]; then
echo "match"
match=1
echo $match
break
fi
done < LoginsMaintMenu.txt
echo $match
return $match
}
echo $username $password
if login "${username}" "${password}"; then
echo "FAIL"
else
echo "success"
fi
这篇关于bash脚本变量的作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!