Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
2  
I suggest to remove ( after do and ) before done. – Cyrus Aug 6 '16 at 19:31
    
Please take a look: shellcheck.net – Cyrus Aug 6 '16 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 '16 at 19:38
    
See choroba's answer. – Cyrus Aug 6 '16 at 19:43

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.