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

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

问题描述

以下带有调试选项set -e -v"的脚本仅在变量的先前值为零时才会在增量运算符处失败.

#!/bin/bash设置 -e -v我=1;让我++;echo "我还在"我=0;让我++;echo "我还在"我=0;((i++));echo "我还在"

bash(GNU bash,版本 4.0.33(1)-release (x86_64-apple-darwin10) 以及 GNU bash,版本 4.2.4(1)-release (x86_64-unknown-linux-gnu))

有什么想法吗?

解决方案

我的问题的答案是不要使用let(或shift,或...)但要使用

i=$((i+1))

当尝试通过使用

设置退出非零状态代码"来检查 bash 脚本时

set -e

bash 手册指出 set -e 具有如果简单命令以非零状态退出,则立即退出."的效果.

不幸的是let(以及shift 和...)返回计算结果('如果最后一个arg 的计算结果为0,则返回1;否则返回 0').因此,不是状态代码,而是某种类型的返回值.有时这个返回值将是零,有时是一,具体取决于计算.因此 set -e 将导致脚本根据您的计算结果退出!!!除非您永远不使用它或求助于

让我++ ||真的

正如 arnaud576875 所指出的那样,顺便说一句,它增加了额外的 CPU 负担.

使用

let ++i

仅适用于 i 不为 -1 的特定情况,如 let i++ 仅适用于 i 不为 0 的情况.因此是半解.

虽然我喜欢 Unix,但我不会有任何其他方式.

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"

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))

any ideas?

解决方案

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

i=$((i+1))

when trying to check a bash script by setting 'exit on non-zero status code' with

set -e

The bash manual states that set -e has the effect of 'Exit immediately if a simple command exits with a non-zero status.'.

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

as pointed by arnaud576875 which btw adds extra CPU burden.

Using

let ++i

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.

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

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

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