How to assign results from a printf statement to a variable (for leading zeros)?

I am writing a shell script (Bash on Mac OS X) to rename a bunch of image files. I want the results to be:

frame_001 frame_002 frame_003 

and etc.

Here is my code:

 let framenr=$[1 + (y * cols * resolutions) + (x * resolutions) + res] echo $framenr: let framename=$(printf 'frame_%03d' $framenr) echo $framename 

$framenr looks correct, but $framename always becomes 0 . Why?

+4
source share
1 answer

The let command forces an arithmetic evaluation, and the reference "variable" does not exist, so you get the default value of 0.

 y=5 x=y; echo $x # prints: y let x=y; echo $x # prints: 5 

Do this instead:

 framenr=$(( 1 + (y * cols * resolutions) + (x * resolutions) + res )) echo $framenr: # if your bash version is recent enough printf -v framename 'frame_%03d' $framenr # otherwise framename=$(printf 'frame_%03d' $framenr) echo $framename 

I remember reading somewhere that $[ ] deprecated. Use $(( )) instead.

+8
source

All Articles