fbpx for Command in Linux: Create Loops in Shell Scripts | Certificação Linux

for Command in Linux: Create Loops and Automate Shell Scripts

📅 01/01/2019 ⏱ 2 min ✍️ Uira Ribeiro
Linuxcommands
for Command in Linux: Create Loops and Automate Shell Scripts
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

The shell has structures to test conditions and execute certain sequences of programs multiple times (loop), until the tested condition is satisfied.

The three commands that enable this are the for (until), the while (while it's true) and until (while it's false).

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

See a simple example:

$ for numero in um dois três quatro cincodoecho "Contando: $numero"done 
Contando: um
Contando: dois
Contando: três
Contando: quatro
Contando: cinco

The same command can be written on a single line:

$ for numero in um dois três quatro cinco; do echo "Contando: $numero"; done

See the example:

$ ls -1 > lista_arquivos.txt

You can now use for to execute various commands for each file in 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_ar­quivos.txt file to the $i variable.

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

Then it 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 é um arquivo “; else echo “$i não é um arquivo”; fi ; done
Desktop não é um arquivoDocuments não é um arquivoDownloads não é um arquivoHR_PROFESSOR.sql é um arquivo

In this line, the result of the ls -1 command is placed in the $i variable; Then each line of the $i variable is tested to see if it's a file; if it's true, a phrase will be displayed, and if it's false, another phrase.

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

Liked it? Share

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp