bash脚本写在一个文件执行时间 [英] bash script write executing time in a file
问题描述
我需要写在一个txt文件来执行这个命令的时间:
I need to write the time taken to execute this command in a txt file:
time ./program.exe
我
如何在bash脚本呢?
How can I do in bash script?
我尝试用>> TIME.TXT
但是,这并不正常工作(输出不会去文件并执行到屏幕)。
I try with >> time.txt
but that doesn't work (the output does not go to file and does go to the screen).
推荐答案
获得时间
在庆典
写文件是艰苦的工作。这是一个庆典
内置命令。 (在Mac OS X中,有一个外部命令,的/ usr / bin / time会
,也做了类似的工作,但使用不同的输出格式和更少的顽抗。)
Getting time
in bash
to write to a file is hard work. It is a bash
built-in command. (On Mac OS X, there's an external command, /usr/bin/time
, that does a similar job but with a different output format and less recalcitrance.)
您需要使用:
(time ./program.exe) 2> time.txt
它写入标准错误(因此 2 - ;
符号)。但是,如果你不使用子shell(括号),这是行不通的;输出还是对屏幕。
It writes to standard error (hence the 2>
notation). However, if you don't use the sub-shell (the parentheses), it doesn't work; the output still comes to the screen.
此外,没有一个子shell,你可以使用:
Alternatively, and without a sub-shell, you can use:
{ time ./program.exe; } 2> time.txt
请注意开括号和分号后面的空格;两者都需要在一行。大括号必须出现在那里的命令可能出现,并且必须是独立的符号。 (如果你努力奋斗的话,你会想出 ...;} |东西
或 ...;} 2 - ;&放大器; 1
这两个标识支架作为一个独立的象征,但如果你尝试 ...;} XYZ
,外壳(可能)无法找到一个名为} XYZ
命令,虽然。)
Note the space after the open brace and the semi-colon; both are necessary on a single line. The braces must appear where a command could appear, and must be standalone symbols. (If you struggle hard enough, you'll come up with ...;}|something
or ...;}2>&1
. Both of these identify the brace as a standalone symbol, though. If you try ...;}xyz
, the shell will (probably) fail to find a command called }xyz
, though.)
我需要在更多的终端上运行更多的命令。如果我这样做:
I need to run more command in more terminal. If I do this:
xterm -xrm '*hold: true' -e (time ./Program.exe) >> time.exe & sleep 2
这是行不通的,并告诉我语法错误:?(意外
如何解决这个问题。
您需要做的是这样的:
xterm -xrm '*hold: true' -e sh -c "(time ./Program.exe) 2> time.txt & sleep 2"
关键变化是运行的脚本从参数到 -c
选项来的壳;您可以替换 SH
与 /斌/庆典
或等效的名称。这应该让周围的任何语法错误的问题。我不太清楚是什么原因引发的错误,虽然如此,有可能是对付它更简单,更好的方法。这也是可以想象,的xterm
的 -e
选项只需要一个字符串参数,在这种情况下,我想你'D使用:
The key change is to run the shell with the script coming from the argument to the -c
option; you can replace sh
with /bin/bash
or an equivalent name. That should get around any 'Syntax error' issues. I'm not quite sure what triggers that error, though, so there may be a simpler and better way to deal with it. It's also conceivable that xterm
's -e
option only takes a single string argument, in which case, I suppose you'd use:
xterm -xrm '*hold: true' -e 'sh -c "(time ./Program.exe) 2> time.txt & sleep 2"'
您可以手动庆典的xterm
以及我可以。
You can manual bash xterm
as well as I can.
我不知道为什么你在后台运行模式,定时程序,但是这是你的问题,不是我的。同样,睡眠2
显然不是必要的,如果搁置:真正的
保持终端打开
I'm not sure why you run the timed program in background mode, but that's your problem, not mine. Similarly, the sleep 2
is not obviously necessary if the hold: true
keeps the terminal open.
这篇关于bash脚本写在一个文件执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!