views:

394

answers:

4
#!/bin/bash -f
files = 'ls /myDir/myDir2/myDir3/'

for file in $files do
    echo $file
    java myProg $file /another/directory/    
done

What i'm trying to do is iterate through every file name under /myDir/myDir2/myDir3/, then use that file name as the first argument in calling a java program (second argument is "/another/directory")

When I run this script: . myScript.sh

I get this error: -bash: files: command not found

What did I do wrong in my script? Thanks!

+1  A: 

strip off the whitespace in and after files = as files=RHS of assignment

Neeraj
+1  A: 

Remove the space surrounding the '=' : change

files = 'ls /myDir/myDir2/myDir3/'

into:

files='ls /myDir/myDir2/myDir3/'

and move the 'do' statement to its own line:

for file in $files
do
   ....
philippe
Did that.Now the error is : syntax error near unexpected token 'echo'
Saobi
yes, because you missed the `;` before `do` - see my answer.
Alnitak
Ok now the problem is, it echos the full path , not just the folder name by itself. I want "myFolder" to be echoed. Not "/myDir/Mydir2/myfolder"
Saobi
try `basename $file`
Neeraj
+2  A: 

Per Neeaj's answer, strip off the whitespace from files =.

Better yet, use:

#!/bin/bash -f
dir=/myDir/MyDir2/MyDir3

for path in $dir/*; do
   file=$(basename $path)
   echo $file
   java myProg $file arg2 arg3
done

Bash is perfectly capable of expanding the * wildcard itself, without spawning a copy of ls to do the job for it!

EDIT: changed to call basename rather than echo to meet OP's (previously unstated) requirement that the path echoed be relative and not absolute. If the cwd doesn't matter, then even better I'd go for:

#!/bin/bash -f
cd /myDir/MyDir2/MyDir3

for file in *; do
   echo $file
   java myProg $file arg2 arg3
done

and avoid the calls to basename altogether.

Alnitak
I want the basename $file to be an input to the java argument. Not just echo it.
Saobi
How's the java program going to read the file without the full path? If that's not a problem, you could just 'cd $dir' at the start of the script.
Alnitak
A: 

quote your variables and no need to use ls.

#!/bin/bash 
for file in /myDir/myDir2/* 
do
  java myProg "$file" /another/directory/    
done