1

I am relatively new to Bash. I wrote a script to generate montage of images using montage utility from imagemagick, by reading list of png files from a text file:

IFS=$'\n'
count=1
for line in `cat pngListGr4`;
do
   montage -tile 4x0 $line $(printf "%03d" $count).png
   ((count=count + 1))
  done
unset IFS 

where pngListGr4 file looks like this:

01.png 02.png 03.png 04.png
05.png 06.png 07.png 08.png
...

Hence I was expecting to generate file 001.png and 002.png as the montage of files 1-4 and 5-8. But instead I am getting error:

montage-im6.q16: missing an image filename `001.png' @ error/montage.c/MontageImageCommand/1795.

However following code works fine in terminal:

$ string_="01.png 02.png 03.png 04.png"
$ montage -tile 4x0 $string_ $(printf "%03d" $count).png

Why my string substitution in my bash script giving such issues?

3
  • This might help: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)? Commented Oct 25, 2019 at 21:51
  • 1
    You are setting IFS to \n to try to read lines, but that means that $string_ will no longer break on spaces. If you copy-paste your script into your terminal, or you copy-paste your terminal command into a script, you'll see that both behave the same way in both places Commented Oct 25, 2019 at 21:54
  • @thatotherguy I tried unsetting IFS before montage, and then resetting it after montage, indeed my script works after that. Can you please write ur comment as answer? Commented Oct 25, 2019 at 22:34

1 Answer 1

1

You are setting IFS to \n to try to read lines, but that means that $string_ will no longer break on spaces in your montage command. The better solution is to use a while read loop which can both get lines and split them up into fields:

count=1
while IFS= read -ra line
do
   montage -tile 4x0 "${line[@]}" "$(printf "%03d" "$count").png"
   ((count++))
done < pngListGr4
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.