庆典集-e和我= 0;让我++不同意 [英] bash set -e and i=0;let i++ do not agree

查看:127
本文介绍了庆典集-e和我= 0;让我++不同意的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与调试选项设置-e -v下面的脚本在失败只有当变量的值为零先前值递增运算符。

the following script with debug option 'set -e -v' fails at the increment operator only when the variable has a prior value of zero.

#!/bin/bash
set -e -v
i=1; let i++; echo "I am still here"
i=0; let i++; echo "I am still here"

i=0; ((i++)); echo "I am still here"

庆典(GNU bash的版本4.0.33(1) - 释放下(x86_64-苹果darwin10),而且GNU的bash,版本4.2.4(1) - 释放(x86_64的未知-Linux的GNU))

bash (GNU bash, version 4.0.33(1)-release (x86_64-apple-darwin10) but also GNU bash, version 4.2.4(1)-release (x86_64-unknown-linux-gnu))

什么想法?

推荐答案

在回答我的问题是不使用的的(或的,或...)但使用

the answer to my question is not to use let (or shift, or...) but to use

i=$((i+1))

试图通过设置检查bash脚本'上非零状态code的退出

set -e

这是 bash的手动状态设置-e 的有退出立即如果一个简单的命令退出时非零状态。

不幸的的(和的和...)返回计算的结果(如果最后一个ARG计算结果为0,让返回1;返回0,否则)。因此,而不是一个状态code一得到某种形式的返回值。而有时这种返回值是零,有时候一个取决于计算。因此设置-e会导致脚本取决于你的计算结果退出!并没有什么做它,除非你要么永远不要使用它,或者诉诸

Unfortunately let (and shift and ...) return the result of the computation ('If the last arg evaluates to 0, let returns 1; 0 is returned otherwise'). So instead of a status code one gets a return value of some sort. And sometimes this return value will be zero and sometimes one depending on the computation. Therefore set -e will cause the script to exit depending on the result of your computation!!! and there is nothing to do about it unless either you don't use it ever or resort to

let i++ || true

为指向的arnaud576875这BTW增加了额外的CPU的负担。

as pointed by arnaud576875 which btw adds extra CPU burden.

使用

let ++i

仅适用于特定的情况下,我不为-1,与的让我++ 的,只有当我不为0,因此一半的解决方案,适用于

works only for the specific case that i is not -1, as with let i++ which works only for when i is not 0. Therefore half-solutions.

我爱的Unix不过,我不会有任何其他方式。

I love Unix though, I wouldn't have it any other way.

这篇关于庆典集-e和我= 0;让我++不同意的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆