如果块总是在Bash中转到else [英] If block always goes to else in Bash

查看:37
本文介绍了如果块总是在Bash中转到else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码段在应放入 elif 时进入 else 语句.

The following segment of code goes to the else statement when it should be going into the elif.

#The following line returns 3, 4 or 5 as the exit code.
$BASH_EXEC adbE.sh "adb $ARGUMENT install $f"
echo "the return code:$?."
if [ $? -eq 5 ]
then
    #do nothing, success
    continue
elif [ $? -eq 4 ]
then
    echo "WARNING"
else
    echo "ERROR"
    break
fi

此部分: echo返回代码:$?." 将其回显到屏幕:返回代码:4.

This part: echo "the return code:$?." echoes this to the screen: the return code:4.

它不显示 WARNING .它仅显示 ERROR ,然后中断包含此代码的 for 循环.

And it does not display WARNING. It only displays ERROR and then breaks the for loop this code is contained in.

我在做什么错了?

这是我尝试导致相同问题的条件比较的变体:

Here are the variations of the condition compare that i have tried resulting in the same issue:

  1. 如果[$?-eq 5]
  2. 如果[$?-eq"5";]
  3. 如果[$?== 5]
  4. 如果[$?=="5";]
  5. 如果[[$?-eq 5]]
  6. 如果[[$?-eq"5";]]
  7. 如果[[$?=="5";]]
  8. 如果[[$?== 5]]
  1. if [ $? -eq 5 ]
  2. if [ $? -eq "5" ]
  3. if [ $? == 5 ]
  4. if [ $? == "5" ]
  5. if [[ $? -eq 5 ]]
  6. if [[ $? -eq "5" ]]
  7. if [[ $? == "5" ]]
  8. if [[ $? == 5 ]]

推荐答案

原因是 $?最后执行的命令的返回代码.您在 if 之前运行 echo 命令,因此您正在测试的是 echo 的返回码,它将始终是0.

The reason for this is that $? is the return code for the last executed command. You are running an echo command before the if, so it is the return code of echo that you are testing, which is always going to be 0.

在您的情况下,还存在另一个问题,因为您正在重新测试 elif 语句中的返回值.初始测试(即 [$?-eq 5] )也会更改 $?的值,因此重新测试将产生意外的结果.

Also, in your case, there is an additional problem caused by the fact that you are retesting the return value in the elif statement. The initial test (i.e. [ $? -eq 5 ]) will also change the value of $?, so retesting it will give an unexpected result.

要解决此问题,请在执行 echo 之前保存以前的返回码,然后将保存的版本用于以后的所有测试:

To fix this situation, save the previous return code before doing the echo, and then use the saved version for all future tests:

ret=$?
echo "the return code:${ret}."
if [ ${ret} -eq 5 ]
then
        #do nothing, success
        continue
elif [ ${ret} -eq 4 ]
then
        echo "WARNING"
else
        echo "ERROR"
        break
fi

这篇关于如果块总是在Bash中转到else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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