TCL脚本尝试捕获

TCL脚本尝试捕获

我有一个 TCL 脚本,它设置多个变量并读取多个文件。它读取的最后一个文件可能包含敏感信息,因此即使在脚本开头发生错误,我也需要确保删除该文件:

#!/usr/bin/expect -f

set timeout 5

set foo [lindex $argv 0]
set bar [lindex $argv 1]
set secret [lindex $argv 2]

if { ! ([file exists "$foo"] && [file executable "$foo"]) } {
    puts stderr "$foo does not exist or is not executable"
    exit 2
}

if { ! ([file exists "$bar"] && [file executable "$bar"]) } {
    puts stderr "$bar does not exist or is not executable"
    exit 3
}

if { ! ([file exists "$secret"] && [file readable "$secret"]) } {
    puts stderr "$secret does not exist or is not readable"
    exit 4
}

#Read secret, do foo, do bar, etc.

file delete $secret

看着尝试我想我可以这样做:

try {
    set foo [lindex $argv 0]
    set bar [lindex $argv 1]
    set secret [lindex $argv 2]

    if { ! ([file exists "$foo"] && [file executable "$foo"]) } {
        puts stderr "$foo does not exist or is not executable"
        exit 2
    }

    if { ! ([file exists "$bar"] && [file executable "$bar"]) } {
        puts stderr "$bar does not exist or is not executable"
        exit 3
    }

    if { ! ([file exists "$secret"] && [file readable "$secret"]) } {
        puts stderr "$secret does not exist or is not readable"
        exit 4
    }

    #Read the file, do foo, do bar, etc.

    file delete $secret
} on error {
    file delete $secret
    exit
}

但我不熟悉 TCL 语法,并且很难在文档中找到内容。这可行吗,还是我需要更改on erroron error {result options}?那么,什么是resultoptions?或者我需要用它来trap代替吗?

答案1

在 Tcl 文档中,可选元素看起来像?this?:示例来自http://tcl.tk/man/tcl8.6/TclCmd/try.htm显示处理程序和“finally”子句是可选的:

尝试 身体处理程序...? ?最后 脚本

在里面条款,变量列表不是可选的,但您可以提供一个空列表。如果您提供{result options}结果是错误消息(对于人类)和选项是一个字典,保存有关错误的特定信息(请参阅返回手册页了解详细信息)。

为了减少代码重复,请使用finally

try {
    # your code here
} on error {} {
    exit
} finally {
    file delete $secret
} 

相关内容