Operating System - Linux
1753731 Members
4726 Online
108799 Solutions
New Discussion юеВ

Issue with "if" statement

 

Issue with "if" statement

Hi,

We are using below given "if" statement in one of our UNIX sh scripts.

if [ -f ${DIR}/Suspect_* -o -f ${DIR}/Prospect_* -o -f ${DIR}/Contact_* -o -f ${DIR}/Activity_* ]
then
echo "Yes"
else
echo "No"
fi

But it gives foolowing syntax error.
"ksh: test: syntax error"

But it is also observed that same sh script runs fine on other UNIX server.

when the above given "if" statement is changed to as given below it runs fine.

if [ -f ${DIR}/Suspect_* ] || [ -f ${DIR}/Prospect_* ] || [ -f ${DIR}/Contact_* ] || [ -f ${DIR}/Activity_* ]
then
echo "Yes"
else
echo "No"
fi

What could be the issue? Why would one command run fine on one server and not on other?

Please provide any information related to this.

Thanks in advance.
4 REPLIES 4
Coolmar
Esteemed Contributor

Re: Issue with "if" statement

Hi,

I know that when I have anything in square brackets I have to make sure to have a space after the first and a space before the last or I get errors.

IE: [-f file.txt] <- I can't do this

[ -f file.txt ] <- this works

OldSchool
Honored Contributor

Re: Issue with "if" statement

different os'es, patches, shells, version of shells could all impact what runs where.

now, my question to you is, does the second version work properly on the first server?
Heironimus
Honored Contributor

Re: Issue with "if" statement

You shouldn't use shell globs (the * character) in your test. It probably won't work how you expect it to.

If you have a Suspect_1 and a Suspect_2, that would expand to "if [ -f Suspect_1 Suspect_2 -o ... ]", which isn't valid syntax. However, "if [ -f Suspect_1 Suspect_2 ]" will work fine because test will just ignore everything after the first filename (at least on HP-UX). And, of course, if you have exactly one matching file it works either way.

If you don't have any Suspect_* files, it could be evaluated as a blank or as the literal string "Suspect_*", depending on which shell you're using and what options are set. That's probably not what you want, but it just happens to work in HP's sh and ksh.
Peter Nikitka
Honored Contributor

Re: Issue with "if" statement

Hi,

in addition to the remarks of Heironimus:
You CAN use filename pattern as argument in a test statement in the ksh, when you change
[ .. ] to [[ ... ]]
Check the manpage for the correct syntax!
Changing your example to

if [[ -f ${DIR}/Suspect_* || -f ${DIR}/Prospect_* || -f ${DIR}/Contact_* || -f ${DIR}/Activity_* ]]
then ...

should do it.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"