0
0
Bash Scriptingscripting~5 mins

for loop with range ({1..10}) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the syntax for i in {1..10} do in a bash script?
It creates a loop that runs 10 times, with the variable i taking values from 1 to 10 in order.
Click to reveal answer
beginner
How do you print numbers 1 to 10 using a for loop with range in bash?
Use:<br>for i in {1..10}; do<br> echo $i<br>done<br>This prints numbers 1 through 10, each on its own line.
Click to reveal answer
intermediate
Can the range in {1..10} be changed to count backwards?
Yes. You can write {10..1} to count down from 10 to 1 in the loop.
Click to reveal answer
intermediate
What happens if you use for i in {1..10..2} in bash?
The loop counts from 1 to 10 in steps of 2, so i takes values 1, 3, 5, 7, 9.
Click to reveal answer
advanced
Why is for i in {1..10} preferred over using seq 1 10 in some cases?
Because {1..10} is a bash brace expansion that is faster and does not require calling an external command like seq.
Click to reveal answer
What will the following bash code print?<br>for i in {1..5}; do echo $((i * 2)); done
A5 10 15 20 25
B1 2 3 4 5
C2 4 6 8 10
DError
How do you write a for loop in bash to count down from 5 to 1?
Afor i in {1..5}; do ... done
Bfor i in {5..1}; do ... done
Cfor i in seq 5 1; do ... done
Dfor i in (5..1); do ... done
What does the '..' operator do in {1..10} in bash?
AIt creates a list of numbers from 1 to 10
BIt performs a subtraction
CIt is a syntax error
DIt creates a string '1..10'
Which of these is a valid way to loop over numbers 1 to 10 in bash?
Afor i in (1..10); do echo $i; done
Bfor i in <1..10>; do echo $i; done
Cfor i in [1..10]; do echo $i; done
Dfor i in {1..10}; do echo $i; done
What will for i in {1..10..3} do?
ALoop from 1 to 10 in steps of 3
BLoop from 1 to 3 ten times
CLoop from 3 to 10 in steps of 1
DSyntax error
Explain how to use a for loop with a range in bash to print numbers 1 to 10.
Think about how to write a loop that repeats 10 times with numbers from 1 to 10.
You got /4 concepts.
    Describe how to modify the range in a bash for loop to count backwards or use steps.
    Consider how the numbers inside braces control the loop sequence.
    You got /3 concepts.