Grep time command output

后端 未结 5 1156
长情又很酷
长情又很酷 2021-02-02 06:38

Using time ls, I have the following output:

$ time ls -l 
total 2
-rwx------+ 1 FRIENDS None 97 Jun 23 08:59 location.txt
-rw-r--r--+ 1 FRIENDS None         


        
5条回答
  •  萌比男神i
    2021-02-02 07:19

    time writes its output to stderr, so you need to pipe stderr instead of stdout. But it's also important to remember that time is part of the syntax of bash, and it times an entire pipeline. Consequently, you need to wrap the pipeline in braces, or run it in a subshell:

     $ { time ls -l >/dev/null; } 2>&1 | grep real
     real   0m0.005s
    

    With Bash v4.0 (probably universal on Linux distributions but still not standard on Mac OS X), you can use |& to pipe both stdout and stderr:

    { time ls -l >/dev/null; } |& grep real
    

    Alternatively, you can use the time utility, which allows control of the output format. On my system, that utility is found in /usr/bin/time:

    /usr/bin/time -f%e ls -l >/dev/null 
    

    man time for more details on the time utility.

提交回复
热议问题