1834149 Members
2298 Online
110064 Solutions
New Discussion

test oddity

 
SOLVED
Go to solution
Steve Sauve
Frequent Advisor

test oddity

Hello all,
A few days I wrote a script to kill off old hung processes on a system. One of the checks I do is to run a ps -ef and grab the 6th field. If it's a question mark then the process is ok (as that means the time stamp is still the time), if it's anything else then it's an old process and should be killed (as the time stamp has converted to month/day and therefore created a new field).
Anyway it works fine, except that I noticed that processes that had a date of the 7th weren't being killed. After looking into this a bit I found that when I compare [ $x != ? ] (with the value of $x being 7) it considers them to be equal. Below is a short test script that shows the issue. Anyone know why this is?

a=1
while [ $a -lt 10 ]
do
if [ $a != ? ]
then
echo "not equal"
else
echo "equal"
fi
a=`expr $a + 1`
done
5 REPLIES 5
Mark Greene_1
Honored Contributor
Solution

Re: test oddity

you have to escape the ? with the \ thus:

if [ $a != \? ]

so that the script interpreter does not use the ? as a special character. Running your example script in ksh with the -x option to debug, you can see it makes 1=1.

mark
the future will be a lot like now, only later
Steve Sauve
Frequent Advisor

Re: test oddity

Thanks that did fix it. Also tried it on a FreeBSD, HP-UX 11 and 11i box. In all those cases it worked fine w/o the slash. I wonder why it was just the number 7 that didn't work....

Anyway, thanks again :)

Steve
Darrell Allen
Honored Contributor

Re: test oddity

Hi Steve,

Do you have a file named 7 in the directory where you run the script? That would cause the problem.

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
Steve Sauve
Frequent Advisor

Re: test oddity

huh..in fact I do. Just got rid of it and suddenly 7 isn't equal to ? anymore :)

Darrell Allen
Honored Contributor

Re: test oddity

Yep, figured as much. As you already know from Mark's reply, you need to escape the ? so the shell won't expand it. You could also quote it ("?").

The shell turns ? (unless escaped or quoted) into the list of files in the current directory named with 1 character. 7 happened to be the first (or only one) in your directory. If you had files named 3 and 7, 3 would not have "worked" and 7 would have "worked".

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)