for循环中的变量在shell脚本中消失

时间:2017-08-01 05:26:06

标签: shell loops variables unix

我在for循环中的if循环中使用结果变量。当我在文件末尾打印结果时,我得到" SERVER_STATUS:错误",但我想得到" SERVER_STATUS:成功"。我应该改变什么来获得受尊重的输出?

result="SERVER_STATUS:error"
  for i in $(seq 1 10)
  do
   if [ "$i" = 4 ]; then
    result="SERVER_STATUS:success"
    echo $result
    break
   fi
  done


echo "$result"

注意:我使用的是shell脚本。

Update1:​​ -

如果我使用带变量的导出,它可以按我的意愿工作。它有什么问题吗?

 result="SERVER_STATUS:error"
      for i in $(seq 1 10)
      do
       if [ "$i" = 4 ]; then
        export result="SERVER_STATUS:success"
        echo $result
        break
       fi
      done


    echo "$result"

1 个答案:

答案 0 :(得分:0)

尝试替换该行:

if [ "$i" = 4 ]; then

with
if [ "$i" = "4" ]; then

or
if [ $i -eq 4 ]; then