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).
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values.
In Bash, printf
is provided by the shell (see the bash(1) manpage, search for "printf"), so you don't even have the (minimal) overhead of fork()
and exec()
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 -v
argument; your script fragment could be rewritten as:
for ((i=23; i<42;i++)); do
printf -v ii "%02i\n" $i
sh ../myprogram $ii
done
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With