Goulash
Goulash

Reputation: 3848

Bash won't change variable value

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

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, $reload remains as 0, the output is similar to this (apache does not get reloaded):

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

Why won't my bash variable change??

Upvotes: 2

Views: 11742

Answers (1)

johnsyweb
johnsyweb

Reputation: 141988

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

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

Upvotes: 6

Related Questions