[root@ntp tcl]# vi timed-run.tcl
exec tclsh "$0" ${1+"$@"}
#
# run a program for a given amount of time,
# aborting after the number of seconds
#
# Usage:
# tclsh timed-run.tcl 20 long_running_program program_args
#
# Author: Jeff Hobbs, based off shorter example by Don Libes
#
# This is required to declare that we will use Expect
package require Expect
proc usage {} {
puts stderr "usage: $::argv0
"
exit 1
}
if {$argc < 2} { usage }
# timeout value is first to be passed in
set timeout [lindex $argv 0]
if {![string is integer -strict $timeout]} { usage }
# program and args are the rest
set cmd [lrange $argv 1 end]
# invoke the cmd with spawn
eval spawn $cmd
# just call expect and wait for it to timeout or eof to occur
expect
运行结果:
[root@ntp tcl]# ./timed-run.tcl
usage: ./timed-run.tcl
以下调用 vmstat 运行时间长1秒,自然退出
[root@ntp tcl]# ./timed-run.tcl 9 vmstat
spawn vmstat
procs memory swap io system cpu
r b w swpd free buff cache si so bi bo in cs us sy id
0 0 0 0 835304 43340 90120 0 0 0 4 83 40 0 0 100
以下调用 vmstat 运行时间长9秒,超时退出
[root@ntp tcl]# ./timed-run.tcl 9 vmstat 1
spawn vmstat 1
procs memory swap io system cpu
r b w swpd free buff cache si so bi bo in cs us sy id
1 0 0 0 835304 43340 90120 0 0 0 4 83 40 0 0 100
0 0 0 0 835304 43340 90120 0 0 0 0 1019 33 0 0 100
1 0 0 0 835300 43340 90120 0 0 0 0 1024 48 0 0 100
0 0 0 0 835980 43340 90108 0 0 0 272 1046 88 0 0 100
0 0 0 0 835980 43340 90108 0 0 0 0 1029 57 0 0 100
0 0 0 0 835980 43340 90108 0 0 0 0 1035 59 0 0 100
0 0 0 0 835980 43340 90108 0 0 0 0 1048 91 1 1 98
0 0 0 0 835980 43340 90108 0 0 0 0 1031 51 0 0 100
0 0 0 0 835980 43340 90108 0 0 0 12 1023 54 0 0 100
1 0 0 0 835980 43340 90108 0 0 0 0 1016 38 0 0 100
[root@ntp tcl]#
[root@ntp tcl]# cat timed-run.tcl
#!/bin/sh
# \
exec tclsh "$0" ${1+"$@"}
优点:
1,二进制文件的位置不需要填入,它可以在你的 shell 查找路径中的任何地方。
2,突破了#!只有30个字符的限制
3,再shell中, 第2行是注释,第3行不是.但是在tcl中, \是连接符号,下一行依旧是注释.所以只有shell有机会执行第3行.
语句导致 shell 停止处理而启动 tclsh 来重新处理整个脚本。当 tclsh启动时,因为第二行的反斜线导致第三行被作为第二行注释的一部分,它把所有三行都作为注释对待。
exec tclsh "$0" ${1+"$@"}
很多地方是这样表达:
exec wish "$0" "$@"
[root@ntp tcl]# vi test
#!/bin/sh
# \
echo hello
echo $0
echo ${1+"$@"}
echo "$@"
[root@ntp tcl]# ./test 1 2 3
hello
./test
1 2 3
1 2 3
可见两者没有太大的区别.
$::argv0 应该是TCL在双引号中调用系统参数的方法?
阅读(8722) | 评论(0) | 转发(0) |