1

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.
    – Cyrus
    Aug 6, 2016 at 19:31
  • Please take a look: shellcheck.net
    – Cyrus
    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
    – Ruben
    Aug 6, 2016 at 19:38
  • See choroba's answer.
    – Cyrus
    Aug 6, 2016 at 19:43

1 Answer 1

8

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.

Not the answer you're looking for? Browse other questions tagged .