bash 脚本有没有办法获得写入文件失败的实际错误号?

问题描述

也就是说:

$ cp /usr/cat c
$ ./c

(不同的窗口)

$ echo foo > c
-bash: c: Text file busy
$ echo $?
1

从技术上讲,内部实际写入返回 -ETXTBSY (-26)。有没有办法使用常规 bash 工具获取该代码而不是 1?缺少解析文本或编写简短的 C 程序(这是在一个奇怪的控制环境中)。

解决方法

有没有办法得到那个代码

您可以编写一个打印 errno 的内置模块。

以下源代码另存为geterrno.c

#include <config.h>
#if defined (HAVE_UNISTD_H)
#include <unistd.h>
#endif
#include <stdio.h>
#include <sys/types.h>
#include "posixstat.h"
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include "posixtime.h"
#include "bashansi.h"
#include "shell.h"
#include "builtins.h"
#include "common.h"
#include "bashgetopt.h"

static int geterrno_builtin(WORD_LIST *list) {
    printf("%d\n",errno);
    return (EXECUTION_SUCCESS);
}

static char *doc[] = {
    "geterrno: prints errno",NULL
};

struct builtin geterrno_struct = {
    "geterrno",geterrno_builtin,BUILTIN_ENABLED,doc,"getrrno: prints errno",};

编译并加载:

$ gcc -DHAVE_CONFIG_H -DSHELL -I/usr/include/bash -I/usr/include/bash/include -I/usr/include/bash/builtins -I/usr/lib/bash -fPIC -shared -o libgeterrno.so
$ enable -f ./libgeterrno.so geterrno

在那之后,你可能会很幸运:

$ geterrno ; echo a > c ; geterrno
0
bash: c: Text file busy
26

使用常规的 bash 工具?

不,那是不可能的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...