0

So I have a bash script with a function that I call a few times. The first time its called it works as expected but any further calls give unexpected results

function doSomething(){
    objFiles="$(dirname "$1")/*.obj";
    for objFile in $objFiles;
    do
        echo "*****IN HERE***** - objfile is \"$objFile\"";
        check="${objFile: -9}";
        if [ $check == ".guid.obj" ]
        then
            echo "do nothing...";
        else
            echo "do something with obj file";
        fi;
    done
}

I pass in the path to a file in the same directory as the .obj files im looking for.

So the first time round this is what it outputs

+ objFiles='/usr/local/apache2/htdocs/uploads/3dmodels/2/47/zip test/*.obj'
+ for objFile in '$objFiles'
+ echo '*****IN HERE***** - objfile is "/usr/local/apache2/htdocs/uploads/3dmodels/2/47/zip test/test1.guid.obj"'
+ check=.guid.obj
+ '[' .guid.obj == .guid.obj ']'
+ echo 'do nothing...'

The second time round this is the output

+ objFiles='/usr/local/apache2/htdocs/uploads/3dmodels/2/47/zip test/*.obj'
+ for objFile in '$objFiles'
+ echo '*****IN HERE***** - objfile is "/usr/loc"'
+ check=
+ '[' == .guid.obj ']'
myShellScript.sh: line 142: [: ==: unary operator expected

The first time it finds the .obj file but the second time round all it gets it "/usr/loc"

any ideas?

1
  • 2
    Run your for loop like: for objFile in "$(dirname "$1")"/*.obj Commented Aug 14, 2014 at 16:07

1 Answer 1

2

It could be a bug somewhere with word splitting and/or pathname expansion. Try changing this:

objFiles="$(dirname "$1")/*.obj";
for objFile in $objFiles;

To this:

for objFile in "$(dirname "$1")"/*.obj

Or

objFiles=("$(dirname "$1")"/*.obj)
for objFile in "${objFiles[@]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.