In Bash, the for
loop can be used to iterate over a list of items. Here are some examples of using the for
loop in Bash:
- Loop over a range of numbers:
for i in {1..10}; do
echo $i
done
- Loop over a list of items:
for i in item1 item2 item3; do
echo $i
done
- Loop over the contents of a file:
for i in $(cat file.txt); do
echo $i
done
- Loop over all files in a directory:
for i in /path/to/directory/*; do
echo $i
done
- Loop over command output:
for i in $(command); do
echo $i
done
- Loop over environment variables:
for i in $(env); do
echo $i
done
You can also use for
loop with in
keyword.
arr=("item1" "item2" "item3")
for i in "${arr[@]}"
do
echo $i
done
You can also use for
loop with while
loop
count=1
while [ $count -le 10 ]
do
echo $count
count=$((count+1))
done
These are just a few examples of how you can use the for
loop in Bash. You can use the for
loop to iterate over any list of items, whether they come from a file, a directory, a command, or any other source.