Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format bash variable for command

Tags:

bash

shell

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).

like image 224
stew Avatar asked Jan 19 '09 20:01

stew


People also ask

What does [- Z $1 mean in Bash?

$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.

What does $() mean in Bash?

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).

What does ${} mean in Linux?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values.


1 Answers

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

like image 73
Commodore Jaeger Avatar answered Oct 17 '22 08:10

Commodore Jaeger