0
0
Bash Scriptingscripting~30 mins

Looping over files and directories in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Looping over files and directories
📖 Scenario: You are organizing files in a folder on your computer. You want to list all the files and directories inside it to see what is there.
🎯 Goal: Create a bash script that loops over all files and directories in the current folder and prints their names.
📋 What You'll Learn
Create a variable holding the list of files and directories
Create a variable to count the number of items
Use a for loop to go through each item
Print each item name
Print the total count of items
💡 Why This Matters
🌍 Real World
Listing files and directories is a common task when managing files on your computer or server. Automating this helps save time and avoid mistakes.
💼 Career
Many IT and DevOps jobs require writing scripts to handle files and directories efficiently. This skill is foundational for automation tasks.
Progress0 / 4 steps
1
Create a variable with all files and directories
Create a variable called items that holds the list of all files and directories in the current folder using ls command.
Bash Scripting
Need a hint?

Use $(ls) to get the list of files and directories.

2
Create a counter variable
Create a variable called count and set it to 0 to count the number of items.
Bash Scripting
Need a hint?

Set count=0 to start counting from zero.

3
Loop over each item and count
Use a for loop with variable item to go through each item in items. Inside the loop, print the item and increase count by 1.
Bash Scripting
Need a hint?

Use for item in $items; do ... done to loop. Use echo "$item" to print. Use count=$((count + 1)) to add one.

4
Print the total count of items
After the loop, print the total number of items using echo and the count variable.
Bash Scripting
Need a hint?

Use echo "Total items: $count" to show the count.