View Full Version : [Shell Scripting] How do I loop through files...
mOOse
11-02-2002, 06:27 AM
How would I loop through all the files in a given directory (passed at the command prompt) and then do something to each of those files.
for i in *; do
echo $i;
done
For example, the above will loop through all the files in the current directory. I need to just loop through the passed directory. I've tried piping it through a "find dirname -maxdepth 1 -type f" command but then the variables inside the loop get reset to 0 upon exiting the loop for some inexplicable reason. Any suggestions?
Bradmont
11-02-2002, 10:50 AM
You can do it this way:
#!/bin/bash
if [ $# -ne 1 ] ;
echo "usage: $0 <directory>" >&2
fi
for file in $1/*; do
echo $file; # or whatever you want to do
done
I've used a couple built-in variables here, they are:
$# -- The number of command line arguments
$0 -- The name of the script (It's grabbed from the command line, so if the script's invoked as "./foo eat a pie", $0 will be "./foo")
$1 -- the first command line argument, "eat" from the above example($2, $3, $4, etc, will be the 2nd, 3rd and 4th)
<edit> I need to larn two speel </edit>
mOOse
11-02-2002, 11:21 AM
Thank You! That's exactly what I wanted. Another quick question, how would I make the above code work recursivly through the directory passed. I guess I could put
for file in $1/* $1/*/* $1/*/*/*; etc but I know there has to be a better way.
Bradmont
11-02-2002, 11:35 AM
here's a nice little example of recursion, it should be pretty easy to adapt to what you want:
http://tldp.org/LDP/abs/html/localvar.html#EX63
However, that might not be the best solution -- instead you could use find, and do something like this:
for file in `find $1`; do ... done
that'll give you the names of all the files in $1 and all its subdirectories.
bwkaz
11-02-2002, 11:35 AM
for i in $(find $1 -type f) ; do
echo $i
doneSomething like that?
GnuVince
11-02-2002, 12:10 PM
mOOse: You could always use a more powerful scripting language:
Ruby:
require "find"
Find.find("/path") { |file|
system("echo #{file}")
}
bwkaz's way should work too
mOOse
11-04-2002, 06:35 AM
Thank you all, you've been great help.
would ask questions again A+++++++++++++ :)
ps I've made a small donation to help support this place
inkedmn
11-08-2002, 02:29 PM
you could do it in python too:
import os
for file in os.listdir("your path here"):
print file,
[edit]
didn't notice you wanted it to be recursive/check subdirectories. python has a method called os.path.walk(), you can see a basic example of it here (http://www.inkedmn.net/code/walktest.py).
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.