Skip to content

For command on Linux (execution loops)

The shell has structures for testing conditions and executing certain program sequences several times (loop), until the tested condition is satisfied.

The three commands that enable this are for (until), while (as long as it is true) and until (as long as it is false).

The for command in Linux allows loops to be made so that one or more commands are executed until a given variable goes through all the values in a given list.

Here’s a simple example:

$ for number in one two three four five from the echo “Counting: $number” done
Counting: one
Counting: two
Counting: three
Counting: four
Counting: five

The same command can be written on a single line:

$ is number in one two three four five; do echo “Counting: $number”; done

See the example:

$ ls -1 > lista_arquivos.txt

You can now use for to execute several commands for each file from the list:

$ for i in $ (cat lista_arquivos.txt); do cp $i $i.backup; mv $i.backup /tmp/backup; done;

This loop assigns each line of the lista_arquivos.txt file to the $i variable.

The expression $ (command) generates a list with the result of the command. It has the same effect as using the command between classes: **command**.

It then executes the commands to rename and move the files until the list is complete.

Now a slightly more complex example, using for with if:

$ for i in `ls -1`; do if test -f $i; then echo “$i is a file “; else echo “$i is not a file”; fi; done
Desktop is not a Documents file it is not a Downloads file it is not a file HR_PROFESSOR.sql is a file

In this line, the result of the ls -1 command is placed in the variable $i; then each line of the variable $i is tested to find out if it is a file; if true, a sentence will be displayed and, if false, another sentence will be displayed.

Learn much more about Linux in our online course. You can register here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it?

Share