Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break for loop if variable is false

Trying to break a for loop if the variable $DEVP doesn't exist.

nme=(Y6T1 Y6-T1 Y6.T1 Yr6T1 Yr6-T1 Yr6.T1 Yr6Term1)
DEVP=(/dev/disk2 /dev/disk3 /dev/disk4 /dev/disk5 /dev/disk6 /dev/disk7 /dev/disk8)

for ((i = 0; i < 7; i++)) ; do 
    if [ ${nme[i]} ${DEVP[i]} = 0 ] ; then
        diskutil eraseDisk FAT32 ${nme[i]} ${DEVP[i]}
    else
        echo “Formatted USBs” ; break
    fi
done

2 Answers

The break works fine

for ((i = 0; i < 7; i++)) ; do
    if [ $i -lt 3 ] ; then
       echo $i
    else            
        echo “Formatted USBs” ; break
    fi
done

Output is:

0
1
2
“Formatted USBs”

, however I'm not sure regarding your if statement, you should probably use -z.

 if [ -z ${DEVP[i]} ] ; then

Have a look here

like image 99
Roman Pustylnikov Avatar answered Jul 02 '26 16:07

Roman Pustylnikov


Your comparison looks like you expect the two strings to contain the single number zero. They never will. If they are empty, they will contain the empty string. (But even then having two string arguments to the left of the comparison operator is a syntax error.)

Anyway, if the actual problem you are trying to solve is that you don't know how many elements these arrays contain, just ask.

for((i=0; i<${#DEVP[@]}; ++i)); do

Of course, if the arrays contain a different number of arguments, you could still end up in a situation where ${nme[i]} is undefined.

    ${nme[i]+:} break

This is rather obscure -- it will expand to the empty string before break (and thus break out of the loop) if the value is unset; if it's set, this is just a : noop.

like image 27
tripleee Avatar answered Jul 02 '26 17:07

tripleee



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!