2

I'd like to evaluate the variable called arduino outside the for loop, but it always gives me 0.

arduino=0
for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do
    (
        syspath="${sysdevpath%/dev}"
        devname="$(udevadm info -q name -p $syspath)"
        [[ "$devname" == "bus/"* ]] && continue
        eval "$(udevadm info -q property --export -p $syspath)"
        [[ -z "$ID_SERIAL" ]] && continue
        dispositivo="/dev/$devname - $ID_SERIAL"
        if [[ $dispositivo == *"Arduino"* ]]; then
            arduino=1
            echo 'CONNECTED DEVICE'
        fi
    )
done

if [ $arduino -eq 1 ]; then
    echo 'CONNECTED DEVICE'
else
    echo 'DISCONNECTED DEVICE'
fi
4
  • 2
    I suggest to remove ( after do and ) before done. Commented Aug 6, 2016 at 19:31
  • Please take a look: shellcheck.net Commented Aug 6, 2016 at 19:34
  • It works!! Thanks, what a very simple solution, can you explain me why? I'm new in bash programming Commented Aug 6, 2016 at 19:38
  • See choroba's answer. Commented Aug 6, 2016 at 19:43

1 Answer 1

9

Parentheses ( ... ) introduce a subshell. Variables in a subshell are inherited from the parent shell, but aren't propagated back to it.

Removing the parentheses should make it work.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.