Skip to content

For loop in Bash script

Overview

Synponis:

for fold in <Interator>
do
    <Statement>
done

note:

can be in various form

Example

Using array and do echo interator

declare
for fold in <Interator>
do
    <Statement>
done

Note:

[1] the double quotes around "${arr[@]}" are really important.

Based on Gabriel Staples comment 1 on Jun 14, 2020 at 20:13

Without them, the for loop will break up the array by substrings separated by any spaces within the strings instead of by whole string elements within the array. ie: if you had declare -a arr=("element 1" "element 2" "element 3"), then for i in \({arr[@]} would mistakenly iterate 6 times since each string becomes 2 substrings separated by the space in the string, whereas for i in "\)" would iterate 3 times, correctly, as desired, maintaining each string as a single unit despite having a space in it.

Usage

[1] Removed basket of folder based on condition

[2] Find and search

Reference