0% found this document useful (0 votes)
3 views4 pages

LOOP

The document provides examples of using for and while loops in a Bash script. It demonstrates a simple for loop to iterate through numbers, an array of fruits, files in a directory, and command output. Additionally, it showcases a while loop for counting and simulating a waiting period.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

LOOP

The document provides examples of using for and while loops in a Bash script. It demonstrates a simple for loop to iterate through numbers, an array of fruits, files in a directory, and command output. Additionally, it showcases a while loop for counting and simulating a waiting period.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

For loop

#!/bin/bash

echo "Simple for loop:"


for i in {1..5}; do
echo "Iteration $i"
done

echo ""

echo "Looping through elements of an array:"


fruits=("Apple" "Banana" "Orange" "Grapes")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
echo ""
echo "Looping through files in a directory:"
echo "Files in current directory:"
for file in *; do
echo "$file"
done
echo ""
echo "Looping through command output:"
echo "Current processes running:"
for process in $(ps -eo cmd); do
echo "$process"
done
output
While loop
#!/bin/bash

# Simple counter with while loop


counter=1
echo "Counting with while loop:"
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++))
done

echo ""

# Simulate waiting with a while loop


echo "Waiting simulation with while loop:"
seconds=5
while [ $seconds -gt 0 ]; do
echo "Waiting for $seconds seconds..."
sleep 1
((seconds--))
done
echo "Done waiting!"
output :

You might also like