1

I am writing this Bash script:

count=0   
result

for d in `ls -1 $IMAGE_DIR | egrep "jpg$"`
do

    if (( (count % 4) == 0 )); then
                result="abc $d"

                if (( count > 0 )); then
                    echo "$result;"
                fi

        else
            result="$result $d"
        fi

        (( count++ ))

done

if (( (count % 4) == 0 )); then
    echo $result
fi

The script is to concate part strings into a string when the value is divided by 4 and it should be larger than 0.

In the IMAGE_DIR, I have 8 images,

I got outputs like this:

abc et004.jpg
abc et008.jpg

But I would expect to have:

abc et001.jpg et002.jpg et003.jpg et004.jpg;
abc et005.jpg et006.jpg et007.jpg et008.jpg;

How can I fix this?

2
  • Perhaps Code Review would be a better place to ask a question like this? Commented Oct 27, 2011 at 15:16
  • 1
    As a side note, you should avoid getting too comfy with backticks, as they don't nest. Just use $(...) instead. Also your for loop will fail horribly if you have jpg files with spaces (say ls | grep | while read d; do ...). Commented Oct 27, 2011 at 15:22

3 Answers 3

7

The = operator must always be written without spaces around it:

result="$result $d"

(Pretty much the most important difference in shell programming to normal programming is that whitespace matters in places where you wouldn't expect it. This is one of them.)

Sign up to request clarification or add additional context in comments.

Comments

2

Something like this?

count=0   

find $IMAGE_DIR -name "*.jpg" |
while read f; do
        if (( (count % 4) == 0 )); then
                result="abc $f"

                if (( count > 0 )); then
                        echo $result
                fi

        else
                result="$result $d"
        fi

        (( count++ ))
done

2 Comments

Thanks, this is promising. I think I should declare result outside of the loop right? I have updated my code but I think I miss something to concate the string... I am still finding the error. Do you any idea?
never mind, my solution is working now, I should put echo in front. Thanks a lot!
1

Something like this (untested, of course):

count=0 result=

for d in "$IMAGE_DIR"/*jpg; do
   (( ++count % 4 == 0 )) &&
     result="abc $d"
   (( count > 0 )) &&
     printf '%s\n' "$result" ||
      result+=$d
done

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.