【问题标题】:time command don't let me use -f with bash functionstime 命令不允许我将 -f 与 bash 函数一起使用
【发布时间】:2014-11-10 02:07:25
【问题描述】:

我想在 bash 脚本中使用 time 命令来计算某个函数的运行时间,但是当我尝试调用它以使用它的任何选项测量脚本的函数之一时,time 命令会给我错误消息,比如我想使用的'--format'。

如果我从终端使用任何命令的“时间 [...]”,也会发生同样的事情。但是,从终端使用它,当我输入 '/usr/bin/time [...]' 而不仅仅是 'time [...]' 时,它可以工作,但是当我调用 '/usr/bin/time ANY_FUNCTION_INSIDE_ANY_SCRIPT [ arguments]' 在脚本中,它抱怨调用的函数不是有效的命令。

test.sh 代码:

#!/bin/bash

testime ()
{
    printf "test message is \"$1\" \n"
    printf "just testing...\n"
    sleep 5
    read -p "enter something: " buffer
    echo $buffer
}

time -f "testime() finished after %E" testime "damn!"
printf "Bye bye!\n\n"
exit

输出:

$ ./test.sh
./test.sh: line 12: -f: command not found

real    0m0.001s
user    0m0.000s
sys     0m0.001s
Bye bye!

但是...如果我使用没有选项的时间,例如“-f ...”,如下所示:

[...]

time testime "damn!"
printf "Bye bye!\n\n"
exit

...脚本正常运行,如您所见:

$ ./test.sh
test message is "damn!" 
just testing...
enter something: SOMETHING_I_HAVE_ENTERED
SOMETHING_I_HAVE_ENTERED

real    0m24.050s
user    0m0.000s
sys 0m0.001s
Bye bye!

并且当我调用“/usr/bin/time -f [...]”时,它会在我从终端执行操作时起作用,无论是否使用“-f [...]”,它给我一些这样的输出:

$ ./test.sh
/usr/bin/time: cannot run testime: No such file or directory
Command exited with non-zero status 127
0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 340maxresident)k
0inputs+0outputs (0major+72minor)pagefaults 0swaps
Bye bye!

有人知道为什么会这样吗?

【问题讨论】:

    标签: bash time


    【解决方案1】:

    在最后提及命令和 -f 选项。

    Shell> time testime 'damn!' -f 'testime() finished after %E'
    test message is "damn!"
    just testing...
    enter something: abc
    abc
    
    real    0m7.513s
    user    0m0.000s
    sys     0m0.003s
    

    test命令的用法明确提到需要在options之前给command。

    NAME
           time - time a simple command or give resource usage
    
    SYNOPSIS
           time [options] command [arguments...]
    

    [options] 中仅给出-P,其余为参数。

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      相关资源
      最近更新 更多