Bash for: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 73: Line 73:
=Iterating over a File List=
=Iterating over a File List=


Also see [[Bash Concepts#Globbing|Globbing]].
Use a [[Bash Concepts#Globbing|globbing]] expression after <tt>in</tt> and the shell will replace it with the list of files matching the expression:
 
<pre>
for f in dir/*; do
    echo ${f}
done
</pre>
 
In case no filename match, the for body is executed with he literal expression ("<tt>dir/*</tt>" in the example above).

Revision as of 05:30, 5 March 2016

External

Internal

Overview

The for built-in command expand words, and execute commands once for each member in the resultant list, with i bound to the current member.

   for i in words; do commands; done

Alternatively, for:

   for i do commands; done

commands executes for each positional parameter (as if in "$@" had been specified.

Yes another alternative form:

    for (( i=0; i<${#names[@]}; i++ )); do
        local name=${names[${i}]}
        echo "${name}"
    done

Iterating through $1, $2, $3 ...

     for i do
         echo ${i}
     done

Iterating through a space separated list

    s="a b c"
    for i in ${s}
        do
            echo ${i}
        done

or

     s="a b c"
     for i in ${s}; do echo ${i}; done

Note the use of ";"

Iterating over Lines in the Same bash Process

IFS="$(printf '\n\r')"
for line in $(cat ./file.txt); do
   echo "${line}"
done
IFS="$(printf ' \t\n')"

For more details on for and IFS, see IFS.

Iterating over a File List

Use a globbing expression after in and the shell will replace it with the list of files matching the expression:

for f in dir/*; do
    echo ${f}
done

In case no filename match, the for body is executed with he literal expression ("dir/*" in the example above).