如何解决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 工具?
不,那是不可能的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。