From my bash shell I would like to call a program n times with a different numbered parameter, which has to be in a fixed format like ‘%02i’
One way would be:
for ((i=23; i<42;i++)); do sh ../myprogram `printf '%02i\n' $i` done
Is there a way to improve the printf.. part? I believe this might be a performance bottleneck with more files and makes the line less readable than a built-in function (especially when condensed to a one-liner).
In Bash,
printfis provided by the shell (see the bash(1) manpage, search for ‘printf’), so you don’t even have the (minimal) overhead offork()andexec()to execute a separate command — unless you run it from within backticks. Bash’s built-in printf lets you assign the output to a given variable with the-vargument; your script fragment could be rewritten as:I’m not sure I’d consider that more readable than the original.
The most resource-intensive part of your script fragment is calling your other shell script; I wouldn’t worry about the overhead of calling printf unless further evidence indicates otherwise.
edited to add the difference between backticks and direct execution