Bash Script Variable Scope Issue

旧街凉风 提交于 2019-12-23 04:54:29

问题


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

output:

hello 3333
match
1
0
FAIL

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!

Thanks


回答1:


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



回答2:


The while read ... part of your code (that gets its input from the cat pipe) runs in a subshell. Changes to variables inside that are not visible outside that subshell.

To work around that, change your loop to:

while read ... ; do
  ...
done < LoginsMaintMenu.txt


来源:https://stackoverflow.com/questions/15390635/bash-script-variable-scope-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!