awk - 检查打印是否成功

3

awk 中,print 语句可能无法成功的原因有几个:没有写入指定文件的权限、文件不存在且 awk 无法创建它等。如何测试 awkprint 语句是否成功?我尝试了以下方法:

$ cat printError.awk
BEGIN {
    if (! (print("Hello") > "/this/doesnt/exist")) {
        print "Could not print"
    }
}

但是它给出了语法错误,我认为是因为print是一个语句而不是函数。
$ awk -f printError.awk 
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:         ^ syntax error
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:                                               ^ syntax error
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:                                                 ^ syntax error

编辑: 我在gawk 4.2+上找到了解决方案,但我正在使用的环境只有4.0版本,所以我仍在寻找该版本的解决方案。

1个回答

4
对于gawk 4.2版本,答案在这里:https://www.gnu.org/software/gawk/manual/html_node/Nonfatal.html。但是,在早期版本中似乎没有PROCINFO ["NONFATAL"]。

5.10 Enabling Nonfatal Output

This section describes a gawk-specific feature.

In standard awk, output with print or printf to a nonexistent file, or some other I/O error (such as filling up the disk) is a fatal error.

$ gawk 'BEGIN { print "hi" > "/no/such/file" }' error→ gawk: cmd. line:1: fatal: can't redirect to `/no/such/file' (No error→ such file or directory)

gawk makes it possible to detect that an error has occurred, allowing you to possibly recover from the error, or at least print an error message of your choosing before exiting. You can do this in one of two ways:

For all output files, by assigning any value to PROCINFO["NONFATAL"].
On a per-file basis, by assigning any value to PROCINFO[filename, "NONFATAL"]. Here, filename is the name of the file to which you wish

output to be nonfatal.

Once you have enabled nonfatal output, you must check ERRNO after every relevant print or printf statement to see if something went wrong. It is also a good idea to initialize ERRNO to zero before attempting the output

使用下面的awk程序:
$ cat nonFatal.awk 
BEGIN {
    PROCINFO["NONFATAL"] = 1
    ERRNO = 0
    print "hi" > "/no/such/file"
    if (ERRNO) {
        print("Output failed:", ERRNO) > "/dev/stderr"
        exit 1
    }
}

在gawk 4.0和4.1版本中,该错误仍然是致命的。

$ gawk -f nonFatal.awk 
gawk: nonFatal.awk:4: fatal: can't redirect to `/no/such/file' (No such file or directory)

但在 gawk 4.2.1 中,它可以工作(我已经编译了 gawk 4.2.1 作为 gawk-4.2.1):

$ ./gawk-4.2.1 -f /var/tmp/nonFatal.awk 
Output failed: No such file or directory

非常好的、经过深入研究的答案! - Ed Morton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接