Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variable math expansion not working with printf

Tags:

bash

I'm trying to get a formatted number that increments every time through a while loop.

I've got fnum=$(printf "%03d" $((++num)) ) but the number doesn't increment. fnum is "000" and remains at that.

Of course num=$((++num)) ; fnum=$(printf "%03d" $num) works but I'm wondering why the first one doesn't increment the number.

like image 243
Tony Williams Avatar asked May 25 '26 09:05

Tony Williams


1 Answers

You don't need comamnd-substitution($(..)) in the first place to store the output of printf use the -v option to store it in a variable

printf -v fnum "%03d" $((++num))

Also the num variable is updated in a sub-shell, $(..) runs the command inside in a separate shell. The value of num incremented will never be reflected back in the parent shell.

like image 118
Inian Avatar answered May 30 '26 06:05

Inian