0
0
Bash Scriptingscripting~5 mins

C-style for loop in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a C-style for loop in bash scripting?
A C-style for loop in bash uses the syntax: for (( initialization; condition; increment )); do commands; done. It works like the for loop in C language, controlling the loop with a counter variable.
Click to reveal answer
beginner
Write the syntax of a C-style for loop in bash.
for (( i=0; i<10; i++ )); do # commands done
Click to reveal answer
beginner
How does the increment part work in a C-style for loop in bash?
The increment part updates the loop variable after each iteration. For example, i++ adds 1 to i each time the loop runs.
Click to reveal answer
beginner
What will this loop print? for (( i=1; i<=3; i++ )); do echo $i; done
It will print: 1 2 3 Each number on its own line, counting from 1 to 3.
Click to reveal answer
intermediate
Can you use negative increments in a C-style for loop in bash?
Yes, you can. For example, for (( i=5; i>0; i-- )) will count down from 5 to 1.
Click to reveal answer
What is the correct syntax to start a C-style for loop in bash?
Afor i in 0 1 2 3 4
Bwhile (( i<5 ))
Cfor i=0 to 5
Dfor (( i=0; i<5; i++ ))
What does the increment part in a C-style for loop do?
AChecks if the loop should continue
BUpdates the loop variable after each iteration
CInitializes the loop variable
DEnds the loop
Which of these loops counts down from 3 to 1?
Afor (( i=0; i<3; i++ ))
Bfor (( i=1; i<=3; i++ ))
Cfor (( i=3; i>0; i-- ))
Dfor (( i=3; i<0; i++ ))
What will this loop print? for (( i=0; i<3; i++ )); do echo $i; done
A0 1 2
B1 2 3
C0 1 2 3
D1 2
Can you use a C-style for loop to loop over a list of strings in bash?
ANo, you must use 'for var in list' syntax
BNo, C-style loops only work with numbers
CYes, but only with arrays
DYes, directly with C-style syntax
Explain how a C-style for loop works in bash scripting.
Think about how you set a counter, check it, and change it each time.
You got /5 concepts.
    Write a C-style for loop in bash that counts from 10 down to 1 and prints each number.
    Use decrement operator and condition i>=1.
    You got /4 concepts.