Previously, the answer was presented with what's now the first section as the last section.
POSIX Shell 包括!
操作员
通过研究 shell 规范的其他问题,我最近(2015 年 9 月)注意到 POSIX shell 支持!
操作员。例如,它被列为保留字并且可以出现在a的开头pipeline— 其中简单命令是“管道”的特殊情况。因此,它可以用于if
声明和while
or until
也在 POSIX 兼容的 shell 中循环。因此,尽管我有所保留,但它的应用范围可能比我在 2008 年意识到的更广泛。对 POSIX 2004 和 SUS/POSIX 1997 的快速检查表明,!
都存在于这两个版本中。
请注意,!
操作员必须出现在开始管道的状态代码并否定整个管道的状态代码(即last命令)。这里有些例子。
# Simple commands, pipes, and redirects work fine.
$ ! some-command succeed; echo $?
1
$ ! some-command fail | some-other-command fail; echo $?
0
$ ! some-command < succeed.txt; echo $?
1
# Environment variables also work, but must come after the !.
$ ! RESULT=fail some-command; echo $?
0
# A more complex example.
$ if ! some-command < input.txt | grep Success > /dev/null; then echo 'Failure!'; recover-command; mv input.txt input-failed.txt; fi
Failure!
$ ls *.txt
input-failed.txt
便携式答案——适用于古董贝壳
在 Bourne(Korn、POSIX、Bash)脚本中,我使用:
if ...command and arguments...
then : it succeeded
else : it failed
fi
这是尽可能便携的。 “命令和参数”可以是管道或其他复合命令序列。
A not
command
这 '!'操作符,无论是内置到 shell 中还是由操作系统提供,都不是普遍可用的。不过,编写起来并不难 - 下面的代码至少可以追溯到 1991 年(尽管我认为我在更早之前编写了以前的版本)。不过,我不倾向于在我的脚本中使用它,因为它不可靠。
/*
@(#)File: $RCSfile: not.c,v $
@(#)Version: $Revision: 4.2 $
@(#)Last changed: $Date: 2005/06/22 19:44:07 $
@(#)Purpose: Invert success/failure status of command
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1991,1997,2005
*/
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "stderr.h"
#ifndef lint
static const char sccs[] = "@(#)$Id: not.c,v 4.2 2005/06/22 19:44:07 jleffler Exp $";
#endif
int main(int argc, char **argv)
{
int pid;
int corpse;
int status;
err_setarg0(argv[0]);
if (argc <= 1)
{
/* Nothing to execute. Nothing executed successfully. */
/* Inverted exit condition is non-zero */
exit(1);
}
if ((pid = fork()) < 0)
err_syserr("failed to fork\n");
if (pid == 0)
{
/* Child: execute command using PATH etc. */
execvp(argv[1], &argv[1]);
err_syserr("failed to execute command %s\n", argv[1]);
/* NOTREACHED */
}
/* Parent */
while ((corpse = wait(&status)) > 0)
{
if (corpse == pid)
{
/* Status contains exit status of child. */
/* If exit status of child is zero, it succeeded, and we should
exit with a non-zero status */
/* If exit status of child is non-zero, if failed and we should
exit with zero status */
exit(status == 0);
/* NOTREACHED */
}
}
/* Failed to receive notification of child's death -- assume it failed */
return (0);
}
当执行命令失败时,这会返回“成功”,与失败相反。我们可以争论“不成功地采取任何行动”的选择是否正确;也许它应该在没有被要求执行任何操作时报告错误。 '中的代码"stderr.h"
' 提供简单的错误报告工具 - 我在任何地方都使用它。根据要求提供源代码 - 请参阅我的个人资料页面与我联系。