Alejandro D. Somoza
Alejandro D. Somoza

Reputation: 401

Bash loop involving variables not working

I am trying to write this simple script which converts a bunch of .png images into an animated gif using ImageMagick. My files are called firstNeighboursDistribution_strength_XXXbosons_13window_YYY.png where XXX={0.0 0.001 0.0025 0.005 0.05 0.1 0.15} and YYY={1,3,5...}. The following code won't show any message on console, it seems it's stuck. What's wrong with it?

#$ -S /bin/bash 
LANG=C #Enforce English. Crucial to get decimal *points* (rather than commas)

for f in 0.0 0.001 0.0025 0.005 0.05 0.1 0.15;
do
convert -delay 400 -dispose Background +page firstNeighboursDistribution_strength_$fbosons_13window_*.png -loop 0 Animation_first_neigh_strength_$f.gif;
done

Pleas note the following code does work as expected:

convert -delay 400 -dispose Background +page firstNeighboursDistribution_strength_XXXbosons_13window_*.png -loop 0 Animation_first_neigh_strength_$f.gif;

for any suitable vale of XXX.

Upvotes: 0

Views: 63

Answers (3)

Devesh
Devesh

Reputation: 2054

your f variable should be like ${f}bosnos

Upvotes: 1

Karl Nicoll
Karl Nicoll

Reputation: 16419

You need to put curly braces around your variable name. Bash doesn't try to match variables, if it finds a $ followed by a valid variable name, it will simply use that. So, in your code, Bash assumes that this is the variable name:

$fbosons_13window_

This is because each of the characters between the $ and the * are valid variable name characters. To fix this, you'll need to surround your variable name with { and } to tell bash the exact variable name, like this:

${f}bosons_13window_

The full line of code in the loop would be this:

convert -delay 400 -dispose Background +page firstNeighboursDistribution_strength_${f}bosons_13window_*.png -loop 0 Animation_first_neigh_strength_$f.gif;

As a sidenote, this is recommended for ANY variable that you use as part of a string. Curly braces can resolve a lot of subtle bugs in bash scripts.

Upvotes: 3

P.P
P.P

Reputation: 121357

It's because $fSomething expands the variable fSomething; not f and concatenates Something.

Use braces {} around your variable f:

convert -delay 400 -dispose Background +page firstNeighboursDistribution_strength_${f}bosons_13window_*.png -loop 0 Animation_first_neigh_strength_${f}.gif;

Upvotes: 2

Related Questions