在脚本中使用`set -e`可以防止bash中的((var ++))增量 [英] Using `set -e` in a script prevents ((var++)) increment in bash

查看:59
本文介绍了在脚本中使用`set -e`可以防止bash中的((var ++))增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/bash
set -e
a=0
echo $a
((a++))
echo $a

仅返回0,但删除 set -e 并返回0,然后返回1,为什么((a ++))返回非零状态?

returns only 0, yet remove the set -e and it returns 0 and then 1, why does ((a++)) return a non-zero status?

推荐答案

请综合考虑以下三个事实:

Consider the following three facts, taken in combination:

  • (((a ++))是后递增的-它的返回值取决于发生之前的值.
  • 在数字上下文中,零值为falsey.
  • set -e 指示如果任何未检查的命令具有错误的退出状态,则退出外壳.
  • (( a++ )) is a postincrement -- its return value depends on the value from before the increment takes place.
  • In a numeric context, a zero value is falsey.
  • set -e instructs the shell to exit if any unchecked command has a false exit status.

因此,在bash 4.1之前,针对该情况做出了明确的例外(防止根据算术表达式的退出状态激活 set -e ),其内容评估为0的数字上下文将导致外壳退出.

Thus, prior to bash 4.1 making an explicit exception for the case (preventing set -e from activating based on the exit status of an arithmetic expression), a numeric context whose contents evaluate to 0 will cause the shell to exit.

对于眼前的具体情况,您可以使用预增量-(((++ a))-代替.

For the specific case at hand, you can work around the issue by using a preincrement -- (( ++a )) -- instead.

这是许多方面之一之一,在该行为中 set -e是不直观且容易出错的(除了广泛地跨壳不兼容).因此,它的使用是有争议的.

This is one of the many respects in which behavior of set -e is unintuitive and fault-prone (in addition to being widely incompatible across shells). Its use is thus rightly controversial.

这篇关于在脚本中使用`set -e`可以防止bash中的((var ++))增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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