I'm trying to get my head around this. I have a basic Bash script:
#!/bin/bash
do_exit=0
while [ "$do_exit" == 0 ] ; do
echo $do_exit
do_exit=1
done
This works. However, when I want to set do_exit=1
inside an if
condition:
#!/bin/bash
do_exit=0
while [ "$do_exit" == 0 ] ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
echo $do_exit
do_exit=1
fi & sleep 5;
done
$do_exit
is ALWAYS 0 ... so never exists. What am I doing wrong? I'm have the same issue with "breaking" and "exit 0" when I want to kill te script - it just carries on!)
I must be misunderstanding how variables work in Bash? In Perl (my normal programing language), you can set variables anywhere (with the exception of explicitly setting them in a function)
free
? are you sure it's getting set to something-gt 0
? is theecho
firing?& sleep 5
should probably be&& sleep 5
... but I'm also wondering about the placement of this clause (ie, when exactly do you want the script tosleep
?); as alluded to in Bayou's answer ... a single&
says to spawn a sub-process and put said process in the background in which case the assignment (performed in a sub-process) is not seen by the parent process[
is not part ofif
syntax. It's just one of the infinite number of commands you can use anywhere, including in anif
, but you can useif
without it; for example,if grep -qe pattern file; then...
[
is=
, not==
. In some shells, using==
will cause an error.&
causes the assignment to be ineffective.$(...)
syntax instead; the standard-compliant syntax is easier to nest, doesn't make surprising changes to how backslashes behave within them, etc. -- and the POSIX sh standard has been out since 1992, so you don't need to worry about finding modern shells that don't support it.