Bash script and command definition

Get a little bash script like this:

#!/bin/bash TIME_CMD='/usr/bin/time -f "%E execution time"' ${TIME_CMD} ls 

Only problem: does not work:

 /usr/bin/time: cannot run execution: No such file or directory Command exited with non-zero status 127 "0:00.00 

What am I doing wrong?

+4
source share
2 answers

Try to do it ...

 #!/bin/bash TIME_CMD='/usr/bin/time -f "%E execution time"' eval "$TIME_CMD ls" 

This will use bash to reanalyze the command line after it is created to correctly determine the recognized argument.

+5
source

Saving commands in variables is usually a bad idea (see BashFAQ # 050 for details). The reason it doesn't work, as you expect, is to ignore quoting values ​​inside variables (unless you run it through something like eval , which then leads to other parsing).

In your case, I see three fairly simple ways to do this. First, you can use an alias instead of a variable:

 alias TIME_CMD='/usr/bin/time -f "%E execution time"' TIME_CMD ls 

Secondly, you can use the function:

 TIME_CMD() { /usr/bin/time -f "%E execution time" " $@ "; } TIME_CMD ls 

Third, you can use an array, not just a variable:

 TIME_CMD=(/usr/bin/time -f "%E execution time") "${TIME_CMD[@]}" ls 

Note that with an array you need to expand it using the "${array[@]}" idiom to properly preserve word breaks.

+5
source

Source: https://habr.com/ru/post/1332829/


All Articles