本文介绍了Bash脚本:使用"脚本"从bash脚本命令用于记录会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用剧本命令用于记录一个bash会话。

I am trying to use script command for logging a bash session.

剧本命令从withing bash脚本执行,但只要它被执行时,bash脚本终止。

The script command is executed from withing a bash script but as soon as it is executed, the bash script terminates.

我试图调用使用各种组合总是以同样的结果(bash脚本终止只要调用的命令)命令。我得到的输出如下:

I have tried to invoke the command using various combination always with the same result (termination of the bash script as soon as the command is called). The output that I get is the following:

Script started, file is typescript
root@ubuntu: ...

我也试图与&放调用命令; 到底却又没有运气

谁能告诉我,我应该如何从一个bash脚本调用命令?

Can anyone tell me how should I invoke the command from a bash script?

感谢

推荐答案

我不认为剧本是做什么的,你觉得它在做什么。你的shell脚本并没有停止。它仍在运行。你得到提示,因为剧本正在孕育一个新的外壳。

I don't think script is doing what you think it is doing. Your shell script did not stop. It is still running. You are getting a prompt because script is spawning a new shell.

用例为剧本是:


  1. 启动剧本(产生一个新的shell)

  2. 请命令

  3. 退出外壳(退出)和下降到previous壳

  4. 检查或创建的打印日志文件剧本

  1. start script (spawns a new shell)
  2. do commands
  3. exit shell (logout) and drop to previous shell
  4. examine or print logfile created by script

所以基本上剧本按预期工作。你将不得不寻找另一种方式来实现你想要的。

So basically script is working as expected. You will have to find another way to achieve what you want.

您可以登录脚本像这样执行:

You can log the execution of your script like this:

#! /bin/bash
exec > logfile 2>&1
set -x
FOO=BAR
echo $FOO

说明:


  • EXEC>日志文件2 - ;&放大器; 1 重定向输出和错误到logfile

  • 设置-x 使得bash的打印执行前的每一个命令

  • exec > logfile 2>&1 redirects stdout and stderr to logfile
  • set -x makes bash print every command before executing it

例如:

$ ./foo.sh
$ cat logfile
+ FOO=BAR
+ echo BAR
BAR

这种方法的缺点是,则该脚本将无输出为人类所看到的。一切顺利的日志文件。

Disadvantage of this method is that the script prints no output for humans to see. Everything goes to the logfile.

另外,你可以做到这一点是这样的:

Alternatively you can do it like this:

#! /bin/bash
# nothing special here
FOO=BAR
echo $FOO

然后执行类似这样的:

Then execute like this:

$ script -c "bash -x foo.sh"
Script started, file is typescript
+ FOO=BAR
+ echo BAR
BAR
Script done, file is typescript
$ cat typescript
Script started on Mi 18 Mai 2011 01:05:29 CEST
+ FOO=BAR
+ echo BAR
BAR

Script done on Mi 18 Mai 2011 01:05:29 CEST

这篇关于Bash脚本:使用"脚本"从bash脚本命令用于记录会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:21