0

I would like to sequence through a set of numbers.

A simple example is sequence through 2 numbers, then sleep for 5 seconds before proceeding to the next 2.

For example: 1 2 (sleeping for 5 seconds) 3 4 (sleeping for 5 seconds)

Thank you in advance

0

3 Answers 3

1

You can use this for loop in bash:

for ((i=1; i<10; i+=2)); do echo $i $((i+1)); sleep 5; done

1 2
3 4
5 6
7 8
9 10
Sign up to request clarification or add additional context in comments.

Comments

0

You could do this as well, using the modulo operator %:

declare -i max_value=10 # set it whatever you want
for ((i = 1; i < $max_value; i++)); do
  printf "Number is: $i\n"
  [[ $(( $i % 2 )) == 0 ]] && printf "Sleeping\n" && sleep 5  # sleep when the number is even
  # do whatever...
done

Output:

Number is: 1
Number is: 2
Sleeping
Number is: 3
Number is: 4
Sleeping
Number is: 5
Number is: 6
Sleeping
Number is: 7
Number is: 8
Sleeping
Number is: 9

Comments

0

If your set of numbers is not a simple set of ascending integers like anubhava's response, you can do similar things.

For example, if your sequence is in a list, list.txt:

declare -ai a=($(<list.txt));  ## Read the sequence from list.txt into a
declare -i i l=${#a[@]};
for ((i=0; i<l; i+=2)); do
    echo ${a[i]} ${a[i+1]};
    sleep 5;
done;

If your sequence's numbers are in a string, like s='1,2,3,4,5,6,4,32,25,4,6,4', you could do declare -ai a=(${s//,/ }) to fill a with your numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.