Answers for "bash for loop break and continue"

0

bash continue

########### continue #########

continue [n]


The [n] argument is optional and can be greater than or equal to 1. 
When [n] is given, the n-th enclosing loop is resumed. 
continue 1 is equivalent to continue.

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

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

echo 'All Done!'
OP : 
Number: 1
Number: 3
Number: 4
Number: 5
All Done!


# eq 2 ############

for i in {1..50}; do
  if [[ $(( $i % 9 )) -ne 0 ]]; then
    continue
  fi
  echo "Divisible by 9: $i"
done

OUTPUT : 

Divisible by 9: 9
Divisible by 9: 18
Divisible by 9: 27
Divisible by 9: 36
Divisible by 9: 45

https://linuxize.com/post/bash-break-continue/
Posted by: Guest on August-22-2021
0

bash for loop break and continue

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!

########### continue #########

continue [n]


The [n] argument is optional and can be greater than or equal to 1. 
When [n] is given, the n-th enclosing loop is resumed. 
continue 1 is equivalent to continue.

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

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

echo 'All Done!'
OP : 
Number: 1
Number: 3
Number: 4
Number: 5
All Done!


# eq 2 ############

for i in {1..50}; do
  if [[ $(( $i % 9 )) -ne 0 ]]; then
    continue
  fi
  echo "Divisible by 9: $i"
done

OUTPUT : 

Divisible by 9: 9
Divisible by 9: 18
Divisible by 9: 27
Divisible by 9: 36
Divisible by 9: 45

https://linuxize.com/post/bash-break-continue/
Posted by: Guest on August-22-2021

Code answers related to "Shell/Bash"

Browse Popular Code Answers by Language