2

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??

1
  • find /home/ -type f -name reload.php | egrep -q '/home/.*/info/reload.php' && service apache2 reload Commented Feb 10, 2013 at 1:56

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, whoopsie :o, thanks for your help :D, will accept this an the answer soon as it lets me..
You might as well break after setting reload=1
@glennjackman: I considered that as a performance improvement, but it would change the behaviour of listing which home directories contained the script, so omitted this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.