iterate through all the files in a directory
December 12th, 2006 by Lawrence David
a simple task you might want to do in a shell script is perform some operation on every file in a directory.
here’s the shell of code to do that:
#!/bin/sh
# iterate through all sequence files in this directory
for phy_file in `find $1 -name “*.phy”`
do
echo $phy_file;
done
here, i’m stepping through and printing out every file that ends with the extension “*.phy”. i’m specifying the directory via a command-line argument ($1). this code would be called in the following way:
$ your_script_name.sh /directory_to_search/
Your command does more than you think. Using find(1) means that you’ll search any subdirectories, too, unless you specify search depth.
What you really want is this simpler approach:
for file in *.phy; do
echo $file
done
Oh, I didn’t include the $1 for the directory:
for file in $1/*.phy; do
echo $file
done