0
0
Bash Scriptingscripting~5 mins

for loop (list-based) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax of a list-based for loop in Bash?
A list-based for loop in Bash looks like this:<br>
for item in list; do<br>  commands<br>done
<br>It runs the commands for each item in the list.
Click to reveal answer
beginner
How does a list-based for loop in Bash work?
It takes each item from the list one by one and runs the commands inside the loop for that item.<br>Think of it like checking each item in a shopping list and doing something with it.
Click to reveal answer
beginner
Write a Bash for loop that prints each fruit in the list: apple, banana, cherry.
for fruit in apple banana cherry; do<br>  echo "$fruit"<br>done
<br>This will print each fruit on its own line.
Click to reveal answer
intermediate
Can the list in a Bash for loop be a variable? How?
Yes! You can store the list in a variable and use it like this:<br>
fruits="apple banana cherry"<br>for fruit in $fruits; do<br>  echo "$fruit"<br>done
Click to reveal answer
beginner
What happens if the list in a Bash for loop is empty?
The loop body does not run at all because there are no items to process.<br>It's like having an empty shopping list; you don't do anything.
Click to reveal answer
What does this Bash code do?<br>
for i in 1 2 3; do echo $i; done
APrints 1, then 2, then 3 each on a new line
BPrints 123 on one line
CPrints the string 'i' three times
DGives an error because of missing quotes
Which of these is a valid list for a Bash for loop?
A(apple banana cherry)
B"apple,banana,cherry"
C['apple', 'banana', 'cherry']
Dapple banana cherry
How do you access the current item inside a Bash for loop?
AUsing $current
BUsing the loop variable name, e.g., $item
CUsing $loop
DUsing $this
What will this code print?<br>
list="dog cat"<br>for pet in $list; do echo $pet; done
Adog cat
Blist
Cdog<br>cat
DNothing
What happens if you run a Bash for loop with an empty list?
AThe loop does not run
BThe loop runs once with an empty item
CThe script crashes
DIt prints an error message
Explain how a list-based for loop works in Bash and give a simple example.
Think about how you would repeat an action for each item in a list.
You got /4 concepts.
    Describe how to use a variable as a list in a Bash for loop and why it might be useful.
    Variables can store lists to make loops easier to manage.
    You got /3 concepts.