-
18 June 2010, 10:26
Bash: How to Loop Through the Contents of a Directory
If you use Linux or Mac, you know what Bash is. Knowing this, I'll move right into the code:
for file in $(ls $1); do echo $file doneAs you know, you can specify a directory for
lsto list the contents of. Here, I have just used the first command line argument.$(...)executes the what is between the parentheses and returns its output. As shown above, you can use variables in that expression. In this example, the output oflsis returned and the for-loop iterates over every line, assigning the current line tofile. It should be obvious that the new-line character is the delimiter here.