gpt4 book ai didi

bash - 如何在称为条件的shell函数中可靠地处理错误?

转载 作者:行者123 更新时间:2023-12-03 08:15:52 25 4
gpt4 key购买 nike

使用bash 4.1.5:

#!/bin/bash

set -e

foo()
{
false
echo "argh, I don't want to get there! What about set -e?!"
}

foo && echo "ok"

这将产生以下输出:
argh, I don't want to get there! What about set -e?!
ok

每当调用 foo作为条件时(即 ifwhile&&||等),都会发生此问题。如果作为简单命令调用, foo行为正确。

我发现这种行为令人惊讶且坦率地说很危险,因为这意味着bash函数的行为根据其调用方式而变化。例如,即使像 foofoo && true这样简单的东西也不会产生相同的结果。这非常令人不安!人们只能想象如果 foo执行敏感操作会造成多大的困惑...

有什么解决方法可以用来避免这种情况?

最佳答案

如果失败,为什么不让foo()返回一个非零的退出代码呢?

foo(){
return 1
echo "argh, I don't want to get here! What about set -e?!"
}

关于bash - 如何在称为条件的shell函数中可靠地处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6581387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com