Home > Software engineering >  How does the bash for-loop know that a variable is a file
How does the bash for-loop know that a variable is a file

Time:09-17

I have 3 files in current directory

t1
t2
t3

Command

for x in t* ; do echo $x ; done

returns

t1
t2
t3

How does for loop knows x is a file?

CodePudding user response:

This is due to Bash's Shell-Expansions, and more specifically Filename-Expansions and Pattern-Matching. You are using the * wildcard which matches "Matches any string, including the null string." So any files in the current directory that matching t* will be iterated over in the for loop. In this case it is just t1, t2, and t3.

That being said, Bash itself doesn't have the concept of "files" rather these are simple strings that point to a specific path on the file system, which can then be used with other commands. You can test if something is a file with the -f flag to the test command.

CodePudding user response:

The for-loop does not know anything about files. This is due to the evaluation of the globs.

  • Related