Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash loop through list of numbers except given number

Tags:

bash

loops

to loop through a continous list of numbers in bash I can do

for s in $(seq 1 5);do
   echo ${s}
done

to loop through a continous list of numbers leaving a given number out in python I can do:

list = [s2 for s2 in range(6)[1:] if s2 != s1]
for s1 in list:
   print s1

where list contains all numbers in range except s1

How do I do the same in bash?

like image 902
andrebeu Avatar asked Dec 19 '22 12:12

andrebeu


2 Answers

Just use continue to skip this step:

for s in {1..5}                 # note there is no need to use $(seq...)
do
   [ "$s" -eq 3 ] && continue   # if var is for example 3, jump to next loop
   echo "$s"
done

This returns:

1
2
4             # <--- 3 is skipped
5

From Bash Reference Manual → 4.1 Bourne Shell Builtins:

continue

continue [n]

Resume the next iteration of an enclosing for, while, until, or select loop. If n is supplied, the execution of the nth enclosing loop is resumed. n must be greater than or equal to 1. The return status is zero unless n is not greater than or equal to 1.

like image 91
fedorqui 'SO stop harming' Avatar answered Jan 15 '23 14:01

fedorqui 'SO stop harming'


Add a short circuit evaluation, || (logical OR) :

for s in $(seq 1 5); do
   (( s == 3 )) || echo "$s"
done

(( s == 3 )) checks if $s is equal to 3, if not (||) echo the number.

With the reverse check ($s not equal to 3) and logical AND (&&):

for s in $(seq 1 5); do
   (( s != 3 )) && echo "$s"
done

The classic way, if with test ([), non-equity test:

for s in $(seq 1 5); do
    if [ "$s" -ne 3 ]; then
        echo "$s"
    fi
done

Reverse test, equity check:

for s in $(seq 1 5); do
    if [ "$s" -eq 3 ]; then
        continue
    fi
    echo "$s"
done

continue will make the loop control to go at the top rather than evaluating the following commands.


There is also a bash keyword [[ which behaves similarly in most cases but more robust.

like image 21
heemayl Avatar answered Jan 15 '23 16:01

heemayl