Answers for "bash break"

1

bash break for looop

break [n] #Exit optional given n number of loops
Posted by: Guest on February-12-2021
0

bash break

break [n] 

[n] is an optional argument and must be greater than or equal to 1. 
When [n] is provided, the n-th enclosing loop is exited. 
break 1 is equivalent to break.

### eg 1 ############
i=0

while [[ $i -lt 5 ]]
do
  echo "Number: $i"
  ((i++))
  if [[ $i -eq 2 ]]; then
    break
  fi
done

echo 'All Done!'

OUTPUT:
Number: 0
Number: 1
All Done!

## eg 2 #######################

for i in {1..3}; do
  for j in {1..3}; do
    if [[ $j -eq 2 ]]; then
      break
    fi
    echo "j: $j"
  done
  echo "i: $i"
done

echo 'All Done!'

OUTPUT:
j: 1
i: 1
j: 1
i: 2
j: 1
i: 3
All Done!

## eq 3 #####################

for i in {1..3}; do
  for j in {1..3}; do
    if [[ $j -eq 2 ]]; then
      break 2   #### see here
    fi
    echo "j: $j"
  done
  echo "i: $i"
done

echo 'All Done!'

OUTPUT :

j: 1
All Done!
Posted by: Guest on August-22-2021

Code answers related to "Shell/Bash"

Browse Popular Code Answers by Language