我正在使用 Linux 的“脚本”命令http://www.linuxcommand.org/man_pages/script1.html在交互式 bash 脚本中记录所有输入和输出。
目前我必须调用script
命令,然后运行我的 bash 脚本,然后exit
。
我想在实际的 bash 脚本中运行script
和exit
命令。我该怎么做?
我已尝试过,script -a
但是这对于交互式脚本不起作用。
任何帮助都将不胜感激。
答案1
“script” 分叉一个 shell(或用“-c”指定的命令),所以我认为你不能从你想要“编写脚本”的脚本中调用“script”。
以这个(令人讨厌的)交互式 shell 脚本(称为“fred”)为例:
#!/bin/bash
while read -p 'Pete and Repeat were on a boat. Pete jumped off. Who was left? ' WHO
do
:
done
运行它并将交互“脚本化”到文件中:
[myles@marklar ~]$ script -c ~/fred fred.log
Script started, file is fred.log
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left? Script done, file is fred.log
日志文件包含:
[myles@marklar ~]$ cat fred.log
Script started on Mon 12 Nov 2012 11:44:41 PM EST
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left? Repeat
Pete and Repeat were on a boat. Pete jumped off. Who was left?
Script done on Mon 12 Nov 2012 11:44:51 PM EST
简而言之,据我所知,您必须使用“script”命令调用交互式 shell 脚本。
答案2
您可以使用以下结构轻松地将脚本的所有输出重定向到文件:
exec &> /your/script.log
此外,当您添加以下内容时,bash 允许您记录它执行的所有命令、它接收的所有输入以及它执行的所有扩展:
set -x
如果这是脚本的前两行,那么脚本执行的所有内容都将被记录下来。