Bash 不会改变变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14793814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:31:07  来源:igfitidea点击:

Bash won't change variable value

bash

提问by Mr. King

I am trying to change the variable reloadfrom 0to 1as you can see in my code below:

我正在尝试将变量reload从更改为01如下面的代码所示:

for d in /home/*; do
  u="${d##*/}";
  reload=0;
  echo "Checking $u";
  if [ -e /home/$u/info/reload.php ]; then
    echo "FOUND!";
    reload=1;
  fi
done
echo $reload;
if [ $reload = 1 ]; then
  service apache2 reload
fi

The problem is that it doesn't get changed, $reloadremains as 0, the output is similar to this (apache does not get reloaded):

问题是它没有改变,$reload仍然是0,输出与此类似(apache不会重新加载):

Checking user1
FOUND!
Checking user2
0 #< this should be 1 not 0 :(

Why won't my bash variable change??

为什么我的 bash 变量不会改变?

回答by Johnsyweb

You're resetting reloadfor each user. If the file is not found for the last user, reloadwill be 0when you exit the loop.

您正在reload为每个用户重置。如果没有找到最后一个用户的文件,reload0在您退出循环时出现。

Suggested fixes (with indentation for readability):

建议的修复(带有缩进以提高可读性):

#!/usr/bin/env bash

reload=0
for d in /home/*; do
    u="${d##*/}"
    echo "Checking $u";
    if [ -e /home/$u/info/reload.php ]; then
        echo "FOUND!"
        reload=1
    fi
done
echo $reload
if [ $reload -eq 1 ]; then
    service apache2 reload
fi