Possible Duplicate:
Checking if a directory contains files
I want to see if a directory is empty, so I am using [ as follows:
[ -f "./ini/*"]
And the return value is always 1, even though the directory is not empty.
Any ideas what’s wrong?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try this:
vs.
See the difference? When you put quotes around a string, the shell can’t glob to replace the asterisk with the matching files.
There are multitude of ways to get what you want. Simplest is to use the
lscommand without the test command. Theifstatement takes the output results of the command you give it. The[...]simply are an alias to thetestcommand. These two statements are equivalent:Basically, all the test command does is return a
0if the test is true or a non-zero if the test is false. All theifcommand does is execute theifstatement if the command it’s given returns a0exit code. The reason I’m going all through this is to say let’s forget the test and simply use thelscommand.Assume that you have a file
foo.txt, but no filebar.txt. Try the following:The
> /dev/null 2>&1is used to inhibit all output. Notice that the exit code of thelscommand when a file exists is0while the exit code of thelscommand when the file doesn’t exist isn’t0. (It’s2in this case). Now, let’s use that instead of the test command:Notice I don’t even bother with the test command (which can be the word
testor the[..]).Hope this makes sense to you. It’s sometimes difficult for people to realize that in BASH shell, the
ifcommand and the[...]are two separate commands, and allifis doing is running the command it’s given and then acting depending upon the exit code of the command it runs.