How to iterate over the results of a command
When we write a bash script, we need to iterate over the results of one or more commands and use
those results.
In order to do this, we can use the
for
command. When we use the
for
, we
put in back quotes
``
the command whose output we want to iterate on. For example, we need to find all the
XML files in a directory
(as explained
here)
and then we want to process those files. What we do is to write a command like this:
for FILE in `find . -maxdepth 1 -name '*.xml'`
do
# do something with the file
# for example, we can print the file path
echo $FILE
# or we can move it!
mv $FILE ./ANOTHER_DIR
done
An important note. The back quotes ``
are used to assign the results of a command to
variables. In the above example,
we iterate over each line of the output of the find
command (i.e. on the path of each
file we
discover with find
) by accessing the $FILE variable that we have declared in the
for
statement.