微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

shell – 如何否定进程的返回值?

我正在寻找一个简单的,但跨平台的否定过程,否定一个过程返回的价值。它应该映射0到某个值!= 0和任何值!= 0到0,即以下命令应该返回“yes,nonexistingpath不存在”:
ls nonexistingpath | negate && echo "yes,nonexistingpath doesn't exist."

!! – 运算符是伟大的,但不幸的是不是shell独立的。

以前,答案是现在的第一部分作为最后一部分。

POSIX Shell包括一个!运算符

探讨其他问题的shell规范,我最近(2015年9月)注意到POSIX shell支持!运算符。例如,它列为reserved word,并可以出现在pipeline的开始 – 其中一个简单的命令是’pipeline’的特殊情况。因此,它可以在if语句和while或until环中使用 – 在POSIX兼容的shell中。因此,尽管我有保留,它可能比我在2008年实现的更广泛可用。对POSIX 2004和SUS / POSIX 1997的快速检查显示!出现在这两个版本。

便携式答案 – 与古色古香的贝壳

在Bourne(Korn,POSIX,Bash)脚本中,我使用:

if ...command and arguments...
then : it succeeded
else : it Failed
fi

这是可移植的,因为它得到。 “命令和参数”可以是管道或其他复合命令序列。

不是命令

‘!’操作符,无论是内置于您的shell还是由o / s提供,都不是通用的。这是不可怕的写,虽然 – 下面的代码可追溯到至少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“’中的代码提供了简单的错误报告功能 – 我无处不在使用它。根据要求提供源代码 – 请参阅我的个人资料页面与我联系。

原文地址:https://www.jb51.cc/bash/390553.html

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

相关推荐