Shell scripting debug help - Iterating through fil

2019-05-19 01:12发布

问题:

#!/bin/sh
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:

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

Better yet, use:

#!/bin/sh -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/sh -f
cd /myDir/MyDir2/MyDir3

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

and avoid the calls to basename altogether.



回答2:

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



回答3:

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
   ....


回答4:

quote your variables and no need to use ls.

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


标签: shell