Bash脚本:使用bash脚本中的“script”命令记录会话

时间:2011-05-12 22:08:24

标签: linux bash

我正在尝试使用script命令记录bash会话。

使用bash脚本执行script命令,但一旦执行,bash脚本就会终止。

我尝试使用各种组合调用命令,但总是使用相同的结果(一旦调用命令就终止bash脚本)。我得到的输出如下:

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

我最后还尝试用&调用命令但又没有运气。

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

由于

5 个答案:

答案 0 :(得分:19)

您的shell脚本未终止。它仍然在运行。您正在收到提示,因为script正在生成一个新shell。

script的用例是:

  1. start script(生成一个新shell)
  2. 执行命令
  3. 退出shell(注销)并放到上一个shell
  4. 检查或打印由script
  5. 创建的日志文件

    所以基本上script按预期工作。你必须找到另一种方法来达到你想要的目的。

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

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

    说明:

    • exec > logfile 2>&1将stdout和stderr重定向到logfile
    • set -x在执行之前使bash打印每个命令

    示例:

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

    此方法的缺点是脚本不打印输出供人类查看。一切都进入了日志文件。

    或者你可以这样做:

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

    然后像这样执行:

    $ 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
    

答案 1 :(得分:5)

您的bash脚本仍在运行,但它已经生成了一个新的交互式shell。 bash脚本正在等待script完成,这只会在交互式shell终止时(通过被杀或用户键入exit)来发生。

要在script记录script之后执行命令,请执行以下操作:

script build_log -c 'echo -e "* This line should appear inside the /"build_log/" log file..."'

但是,script将在运行该命令后停止运行。

要在script中运行多个命令,请将这些命令放在另一个bash脚本中,并将bash脚本指定为运行-c选项的命令。

答案 2 :(得分:3)

遵循execve的想法,您还可以使用环境变量:

#!/bin/sh
[ -z "$TYPESCRIPT" ] && TYPESCRIPT=1 exec /usr/bin/script -c "TYPESCRIPT=1 $0 $@"
# your script here...

答案 3 :(得分:2)

您可以在shell脚本中使用技巧来启动脚本或不启动脚本。基于特殊参数,它可以选择使用特殊参数执行自身,以便不再启动脚本。

这很可能解释我的意思:

if [ "$1" != "noscript" ] ; then
        # execute self with the noscript special arg so that the second execution DOES NOT start script again.
        exec script -q -c "$0 noscript $1 $2 $3" /build/buildlog_`date '+%Y%m%d%H%M%S'`.log
        echo Problem in $0, please check.
        exit 1;
fi 
...Rest of the script should follow here.

我试过这个,效果很好。除非你特别关注需要传递的参数类型以及脚本计划被恶意用户使用,否则这应该足够了:)。

答案 4 :(得分:2)

juj的答案很棒,但未能正确传递参数。基本问题是在双引号字符串中使用$@。应该使用$*代替:

#!/bin/sh
[ -z "$TYPESCRIPT" ] && TYPESCRIPT=1 exec /usr/bin/script -c "TYPESCRIPT=1  $0 $*"
# your script here...

以下是$@

的情况

foo.sh

#!/bin/sh
if [ -z $FOO ]
then
    FOO=1 exec $0 $@
else
    ./echo_args.sh "$0 $@"
fi

bar.sh

#!/bin/sh
echo 0 $0
echo 1 $1
echo 2 $2
echo 3 $3

现在./foo.sh with some arguments输出

0 ./bar.sh
1 /path/to/foo.sh with
2 some
3 arguments

这会导致一些参数传递给script而不是第二次执行foo.sh