Bash Script Variable Scope Issue

2019-06-08 17:19发布

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

2条回答
We Are One
2楼-- · 2019-06-08 17:58

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
查看更多
聊天终结者
3楼-- · 2019-06-08 18:04

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
查看更多
登录 后发表回答