Lets say i have to test if file contains a string "mail" , what is the difference between

if grep -q "mail" "file"; then ...

if [ $( grep -l "mail" "file") ]; then ...

[ grep -l "mail" "file" ] && ..

Are there any differences in these or are they globaly the same ( like they would result in the same outcome with any condition inside or command)

  • First will succeed if return code is 0, second will succeed if there is any output from the command and the last should break and say too many args. – 123 Mar 17 '16 at 11:16
if command; then ...

evaluates the exit status of command. 0 is success (evaluates the condition as true).

First of all: [ is (almost) identical with test, hence it expects the command string to comply with its syntax.

if [ $(command) ]; then ...

evaluates the string containing the output of command. In most cases it will not work - see the example below.

[ command ] && ..

grep -l "mail" "file" will be interpreted like this:

  • grep - a string
  • -l - unary operator returning the length of the following string
  • "mail" - a string, will be passed as an argument to the -l operator
  • "file" - a string

Depending on implementation you will get slightly different errors, because the above is asking [ to evaluate a sequence consisting of a string, a number and another string, without any operators. By default [ (as well as test) is a shell built-in, you can compare the error messages with the standalone binary (usually /bin/[ or /usr/bin/[).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.