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

I'm 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

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?



Solution 1:[1]

The let command forces arithmetic evaluation, and the referenced "variable" does not exist, so you get the default value 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:

# or
framename=$(printf 'frame_%03d' $framenr)

echo $framename

And there's printf -v to avoid subshell invocation:

# with bash 3.1+
printf -v framename 'frame_%03d' $framenr

See the manual for printf -v, available from bash 3.1+.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ryenus