在命令行上记录 Unix 命令

bgu*_*uiz 7 unix shell redirection command-line

出于教程的目的,我想将最后一个命令和最后一个命令的输出附加到文本文件中。

例如:ls在我的主目录中执行操作后,我在屏幕上看到了这个

bguiz@sheen:~$ ls
Desktop     Music    Documents
Run Code Online (Sandbox Code Playgroud)

然后我希望能够输入一个命令,该命令会将以下内容附加到名为的文本文件 cmd.txt

$ ls
Desktop     Music    Documents
Run Code Online (Sandbox Code Playgroud)

这个想法是每次我输入一个命令时,我可以将命令本身及其输出记录到同一个文件中,并且在几个命令之后,它将演示一系列特定的命令。我知道这可以手动完成 - 但如果有一个简单的替代方法,为什么要这样做,对吗?

这是我到目前为止已经煮熟的:

echo -n "\$ " >> cmd.txt; echo !-1:p >> cmd.txt; !-1 >> cmd.txt
Run Code Online (Sandbox Code Playgroud)

它有效,但相当笨重,并且有几个问题,例如无法保留确切的屏幕格式。

是更优雅的解决方案吗?


感谢您到目前为止的答案,但我有一个需要与管道一起工作的要求,例如:

ls -lart | grep ^d
Run Code Online (Sandbox Code Playgroud)

需要将其附加到文件中:

$ ls -lart | grep ^d
drwx------ 14 bguiz staff   4096 2010-03-03 15:52 .cache
drwx------  5 bguiz staff   4096 2010-03-03 09:38 .ssh
Run Code Online (Sandbox Code Playgroud)

dmc*_*ten 10

比你一直在尝试的聪明更简单:

$ script cmd.txt
Run Code Online (Sandbox Code Playgroud)

在这里做你想记录的事情

然后点击 Control-d。

如果您愿意,您可以在以后编辑文件以添加注释,并且您可以使用

$ script -a cmd.txt
Run Code Online (Sandbox Code Playgroud)

将更多文本附加到现有文件。

可用选项似乎在实现之间有很大差异。

  • Mac OS X(即 BSD)脚本支持-k将键盘输入记录到命令中
  • GNU 版本(在 linux 系统上找到)支持-c它允许您在原始命令行上指定命令,允许您跳过“在此处输入演示然后点击 control-d”
  • BSD版可通过命令行上指定的命令,但不接受该相反,它必须遵循的输出文件名的标志(在这种情况下需要)。

最后,GNU 版本警告vi在类型脚本中没有很好地表示(我想这个警告同样适用于所有其他使用 curses 的命令)。


mru*_*cci 5

script.sh如果以注释的形式插入注释,请编写如下脚本:

#!/bin/sh -v

# Annotating the behaviour of the ls command
ls -l

# Other comments on the next command
cmd
Run Code Online (Sandbox Code Playgroud)

注意-v第一行的开关:

-v verbose       The shell writes its input to standard error as it is read.
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令执行将 stdout 和 stderr 重定向到文件的脚本cmd.txt

$ ./script.sh > cmd.txt 2>&1
Run Code Online (Sandbox Code Playgroud)

该文件cmd.txt将包含注释、命令及其相关输出,例如:

# Annotating the behaviour of the ls command
ls -l
total 1824
drwxr-xr-x 11 mrucci mrucci    4096 2010-02-14 18:16 apps
drwxr-xr-x  2 mrucci mrucci    4096 2010-02-20 12:54 bin
-rw-------  1 mrucci mrucci  117469 2010-02-25 11:02 todo.txt

# Other comments on the next command
cmd
./testscript.sh: 7: cmd: not foun
Run Code Online (Sandbox Code Playgroud)

PS:记得给脚本授予执行权限:

$ chmod +x script.sh
Run Code Online (Sandbox Code Playgroud)


Dua*_*ane 3

[script.ksh] 使用“script.ksh ls”运行

#!/bin/ksh

OUTPUT="cmd.txt"

if [[ $# -eq 0 ]];then
  print "no command to run"
  exit
fi

# dump command being run to file
echo $@ >> $OUTPUT

# run command and output stdout to the screen and file
$@ | tee -a $OUTPUT
Run Code Online (Sandbox Code Playgroud)