How do i add control to a for loop in a bash shell script?



  • You can run loops until you have gone through all the items or you can run test conditions and decide if you want to continue or drop out of or rather break out of the loop.

           continue [n]
                  Resume the next iteration of the enclosing for, while, until, or
                  select loop.  If n is specified, resume  at  the  nth  enclosing
                  loop.   n  must  be  ≥  1.   If  n is greater than the number of
                  enclosing loops, the  last  enclosing  loop  (the  ``top-level''
                  loop) is resumed.  The return value is 0 unless n is not greater
                  than or equal to 1.
    
           break [n]
                  Exit from within a for, while, until, or select loop.  If  n  is
                  specified, break n levels.  n must be ≥ 1.  If n is greater than
                  the number of enclosing loops, all enclosing loops  are  exited.
                  The  return  value is 0 unless n is not greater than or equal to
                  1.
    

    Take a look at the following script.

    • It takes all the items in the current directory.
    • checks to see if the item is a directory.
    • if it's a directory it continues.
    • prints a message.
    • if the loop finds a directory named rootfs is breaks out of the loop and prints a message.
    #!/bin/bash 
    for Dirname in *
    do 
    [ -d "$Dirname" ] || continue
    echo "$Dirname" is a directory
    [ "$Dirname" = rootfs ] && break
    done 
    
    if [ "$Dirname" = rootfs ];then
    echo "Cannot continue processing rootfs found"
    fi
    

    If there are no directories in your current path the script will print nothing.

    With the use of continue and break we can control the loop.


Log in to reply
 

© Lightnetics 2024