Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

Bash check shows file exists for non-existent files?

Run the following in bash:

   stuff=`rpm -ql <some package> | grep dasdasdfd`

(non existent file in package, exit code = 1, stdout is empty)

  if [ -f $stuff ]; then echo "whaaat"; fi

Above command checks if file exists... but:

file $stuff

Just prints usage info for file... and

stat $stuff

Missing operand...

Can someone please explain why? Is this a bug? Am I doing something wrong? I just want to make sure that a file that's in the package is present on fs

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably need to surround $stuff in quotes

if [ -f "$stuff" ]; then

As a general rule, you almost always want to add quotes around pathnames everywhere you use them.

I find it more useful to think or variables in shell scripting as "macros", which are expanded on first use to their value. This is different from variables in almost every other programming language.

So if $stuff contains hello world (notice the space), it would be the same as if you've typed:

[ -f hello world ]

which is obviously an error.

In this case, you mentioned that you're dealing with a non-existent file, so $stuff is actually empty, which would be like typing:

[ -f ]

Which is actually valid, but always succeeds. This is a bit of obscure test behaviour, from the POSIX spec we read that test always succeeds if there if only a single argument (in this case, the argument is -f):

1 argument:
Exit true (0) if $1 is not null; otherwise, exit false.

This is probably to facilitate the writing of:

[ $variable_that_may_or_may_not_be_defined ]

If you add quotes, you're passing 2 arguments, and more sane things happen:

if [ -f "" ]; then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...