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

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

问题描述

只有当变量的先前值为零时,带有调试选项set -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"

bash(GNU bash,版本 4.0.33(1)-release (x86_64-apple-darwin10) 以及 GNU bash,版本 4.2.4(1)-release (x86_64-unknown-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))

有什么想法吗?

推荐答案

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

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

i=$((i+1))

当尝试通过设置退出非零状态代码"来检查 bash 脚本时,

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

set -e

bash 手册指出 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.'.

不幸的是,let(以及 shift 和 ...)返回计算结果('如果最后一个 arg 计算结果为 0,let 返回 1;否则返回 0').所以不是状态码,而是得到某种返回值.有时这个返回值将是零,有时是一个取决于计算.因此 set -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 指出的那样,顺便说一句,这增加了额外的 CPU 负担.

as pointed by arnaud576875 which btw adds extra CPU burden.

使用

let ++i

仅适用于 i 不为 -1 的特定情况,如 let i++ 仅适用于 i 不为 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.

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

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