How to do something to every file in a directory using bash?


I started with this:

command *

But it doesn't work when the directory is empty; the * wildcard becomes a literal "*" character. So I switched to this:

for i in *; do

which works, but again, not if the directory is empty. I resorted to using ls:

for i in `ls -A`

but of course, then file names with spaces in them get split. I tried tacking on the -Q switch:

for i in `ls -AQ`

which causes the names to still be split, only with a quote character at the beginning and ending of the name. Am I missing something obvious here, or is this harder than it ought it be?

8/21/2009 7:12:14 AM

Accepted Answer

Assuming you only want to do something to files, the simple solution is to test if $i is a file:

for i in * 
    if test -f "$i" 
       echo "Doing somthing to $i"

You should really always make such tests, because you almost certainly don't want to treat files and directories in the same way. Note the quotes around the "$i" which prevent problems with filenames containing spaces.

8/21/2009 7:43:55 AM

find could be what you want.

find . | while read file; do
    # do something with $file

Or maybe like this:

find . -exec <command> {} \;

If you do not want the search to include subdirectories you might need to add a combination of -type f and -maxdepth 1 to the find command. See the find man page for details.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow