How to do something to every file in a directory using bash?
bash, shell
Solution
Assuming you only want to do something to files, the simple solution is to test if $i is a file:
for i in *
do
if test -f "$i"
then
echo "Doing somthing to $i"
fi
done
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.
Problem
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 ... done ``` 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?