return value for find or grep for use as an if statement condition
I am trying to write a script using if statements but I am unclear as to what some linux commands return. for instance could I use the "find" command as the condition for an if statement as shown below?
Code:
if [ $(find /mypath -name main.cpp) ]; then does the find command return true if it finds the file and false if it doesn't? I am wondering the same thing about the grep command. I read the man pages and it says "find" returns a 0 if all files are processed succesfully and other numbers if not. Does that mean it will return a 0 if it finds the file? or does that just mean it returns a 0 if the "find" command runs succesfully without running into problems? |
The program you show returns the text output from find inside the [].
The grep answer is you get 0,1 or 2. You can actually test this faster than posting the question here. Code:
if grep root: /etc/passwd |
Immediately after a command exits, its exit code is stored in the special variable "$?". echo that to see what you'll get, or test it in the usual ways.
But actually you generally don't need to use any kind of test here. The [..] test brackets are just a command like any other, and give an exit code, which is what the if/while/until constructs are actually working with. So you can replace it with just about any command if you want. Code:
if grep -q 'foobar' file.txt ; then Or actually, the way you have it written in the OP may do just as well, since the $(...) will be substituted with the text output of the command. [..] will exit successfully if it finds a text string (although it's better to use the explicit -n/-z test options). The only caveat is that you have to double quote the substitution or else it will probably error out on multi-word strings (too many arguments). The bash/ksh [[..]] extended test doesn't have that problem, by the way, and so is recommended. http://mywiki.wooledge.org/BashFAQ/031 |
May I also suggest that if you are looking for a file, then just test for it:
Code:
shopt -s globstar |
All times are GMT -5. The time now is 01:22 AM. |