简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM