Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

printf

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?

like image 342
Tom Söderlund Avatar asked Sep 22 '13 20:09

Tom Söderlund


1 Answers

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:

# if your bash version is recent enough
printf -v framename 'frame_%03d' $framenr
# otherwise
framename=$(printf 'frame_%03d' $framenr)

echo $framename

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

like image 199
glenn jackman Avatar answered Oct 20 '22 17:10

glenn jackman