What does the expression "for x in *" do?

Asked

Viewed 97 times

3

I saw this expression in a SOEN question, but I did not understand very well what it does

for x in *;
do
    echo $x;
done

This printed the folder list of the directory I was in.

That’s what that expression is for?

What would that be * asterisk?

2 answers

3


This, written the way it is, does the same thing as the command ls

The * is being used as a joker.

Try it this way:

for x in *.zip;do echo $x; done;

You can use the same rules that you use on ls, as an example:

for x in ./*/*.zip;do echo $x; done;

or

for x in /var/log/*.log;do tail $x; done;

As a practical example, the code below clears the content of logs in the development environment:

for x in /var/log/*.log;do echo '' > $x; done;

3

The asterisk indicates the reading of everything in the folder.

The variable X receives the names of the individual files, which are printed by the constructor echo.

  • I didn’t know that the * list folders as well. Interesting!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.