bash中"let"的奇怪错误 [英] A strange error of 'let' in bash

查看:64
本文介绍了bash中"let"的奇怪错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道下面的代码语法是否错误?

I wonder if the code below has wrong syntax ?

#!/bin/bash
set -e
let "time_used = 1 - 1"
echo $time_used

当我运行它时,什么也没打印.该脚本死于 let"time_used = 1-1" .

When I run it, nothing print. The script died on let "time_used = 1 - 1".

如果我在第二行中删除 set -e ,则会得到正确的结果 0 .

If I remove set -e in second line, I get the correct result 0.

为什么会这样?

推荐答案

let是

等同于

(( time_used = 1 - 1 ))

但是壳算法中的0表示错误,并给出错误退出状态,以避免用 -e ||退出true 可以在命令后添加

however 0 in shell arithmetic means false and gives error exit status to avoid to exit with -e || true can be added after command

(( 0 )) || true
let "time_used = 1 - 1" || true

||true 允许对返回错误退出状态的命令绕过" -e 选项,但是我们无法将失败的命令与返回错误的退出状态的命令区分开.另一种选择是使用算术总是返回真实值.

|| true allows to "bypass" -e option for commands returning an error exit status however we can't distinguish a command that failed from a command that returns a false exit status. Other option can be to use arithmetic to return always a truthy value.

(( (time_used = 1 - 1) || 1))

这篇关于bash中"let"的奇怪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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