[英]Bash script: Using "script" command from a bash script for logging a session
我正在尝试使用script
命令来记录 bash 会话。
script
命令是从 bash 脚本执行的,但一旦执行,bash 脚本就会终止。
我尝试使用各种组合调用命令,结果总是相同(调用命令后立即终止 bash 脚本)。 我得到的输出如下:
Script started, file is typescript
root@ubuntu: ...
我还尝试在最后用&
调用命令,但还是没有成功。
谁能告诉我应该如何从 bash 脚本调用命令?
谢谢
您的 shell 脚本没有终止。 它仍在运行。 您收到提示是因为script
正在生成新的 shell。 您看到的提示是来自生成的 shell 的提示。
script
的正常用例是这样的:
script
。 这会产生一个新的外壳。script
创建的日志文件所以基本上script
按预期工作。 你将不得不找到另一种方法来实现你想要的。
您可以像这样记录脚本的执行:
#! /bin/bash
exec > logfile 2>&1
set -x
FOO=BAR
echo $FOO
解释:
exec > logfile 2>&1
将 stdout 和 stderr 重定向到日志文件set -x
使 bash 在执行之前打印每个命令例子:
$ ./foo.sh
# (no output here because everything goes to logfile)
$ 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
现在输出直接可见并保存到日志文件(日志文件的默认名称是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 脚本仍在运行,但它生成了一个新的交互式 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
选项的命令。
按照 execve 的想法,您还可以使用环境变量:
#!/bin/sh
[ -z "$TYPESCRIPT" ] && TYPESCRIPT=1 exec /usr/bin/script -c "TYPESCRIPT=1 $0 $@"
# your script here...
您可以在 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.
我试过这个,效果很好。 除非您特别注意需要传递的参数类型以及脚本计划被敌对用户使用,否则这就足够了:)。
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
的第二次执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.