Bash for: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 70: Line 70:


For more details on <tt>for</tt> and <tt>IFS</tt>, see [[bash Environment Variables#IFS|IFS]].
For more details on <tt>for</tt> and <tt>IFS</tt>, see [[bash Environment Variables#IFS|IFS]].
=Iterating over a File List=
Also see [[Bash Concepts#Globbing|Globbing]].

Revision as of 05:27, 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

Also see Globbing.