views:

93

answers:

3

I want to write a shell script that loops through all directories under a directory, and call a java program with the directory name as an argument at each iteration.

So my parent directory is provided as an argument to the shell script: eg:

. myShell.sh  /myFolder/myDirectory

There are 100 directories under /myFolder/myDirectory. For each "directory_i", i want to run:

java myProg directory_i

If someone can provide me with a working shell script that'll be perfect!

+7  A: 

You could use find.

The myShell.sh script might look a bit like this, this is a version that will recursively process any and all subdirectories under your target.

DIR="$1"
find "$DIR" -type d -exec java myProg {} \;

The exact set of find options available depends on your variety of unix. If you don't want recursion, you may be able to use -maxdepth as Neeraj noted, or perhaps -prune, which starts get a bit ugly:

find "$DIR" \( ! -name . -prune \) -type d  -exec java myProg {} \;

EDIT: Added prune example.

martin clayton
I need complete code, not snippet that may or may not work.
Saobi
And we should do your work for you why?
bmargulies
anyway this answer is complete.
bmargulies
@Saobi - it works for me. I don't have your java program to test with though.
martin clayton
a -maxdepth option if dont want sub directories..
Neeraj
@Saobi - your comment was rude, when people spend time helping you at least make the effort to try out what they suggest
Gregory Pakosz
"plz email me teh codez!" ... too bad we can't downvote comments
glenn jackman
Ok I apologize.
Saobi
+2  A: 
#!/bin/bash -f
files=`ls $1`
for file in $files; do
        if [ -d $file ];then
          java myProg $file
          # java your_program_name directory_i
        fi
done
Neeraj
i intended a backquote at `ls $1` but escaping it wont work although..:P
Neeraj
Can you elaborate on the "# your command here"?
Saobi
A: 
#!/bin/sh
for i in */.; do
  echo "$i" aka "${i%/.}"
  : your_command
done
DigitalRoss