Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting: boolean variable not working properly

Tags:

bash

I am trying to evaluate a boolean variable in Bash scripting, but it always return false.

Here is the code:

DEVICE_FOUND=false
tmp=`adb devices | tail -n+2 | awk '{print $1}'`

echo "$tmp" | while read line
do
    if [ "$DEVICE_ID" = "$line" ]
    then
        echo "Found a device"
        DEVICE_FOUND=true
    fi
done

if ! $DEVICE_FOUND
then
    echo "ERROR: The device "$DEVICE_ID" is not connected"
    exit
fi

Whether or not "Found a device" gets executed or not, I always go into the if statement. When DEVICE_FOUND=true, it should not go in the last if but it does.

I do not understand why is that.

Does anyone please know?

Thank you very much.

like image 800
Jary Avatar asked Jun 25 '26 05:06

Jary


1 Answers

That's because you are setting the true value after the |, i.e. in a subshell. Variable values from a subshell do not propagate back to the parent shell. Get rid of the subshell:

while read line
do
    ...
done <<< "$tmp"
like image 189
choroba Avatar answered Jun 26 '26 21:06

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!