Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

ls "${VMX_DIR}" | grep -q delta > /dev/null 2>&1;

It lists the files in VMX_DIR and then pipes them into grep but what is it doing?

share|improve this question

4 Answers 4

up vote 4 down vote accepted

It's checking to see whether there is a file or path containing delta in ${VMX_DIR} then returns the result via the exit code of grep since grep will return with a normal exit code of 0 if it finds a match, and failure code of 1 if it doesn't. It's useful in bash conditionals.

Here's what it's doing statement by statement:

ls "${VMX_DIR}"

Lists the contents of the directory stored in the path ${VMX_DIR}

| grep -q delta

Pipe the results to grep, searching the results of the directory listing for delta ignoring any output to stout.

> /dev/null 2>&1;

Redirects stdout to /dev/null so it will not be printed. The 2>&1 tells bash to redirect stderr to stdout (which is now going to /dev/null). The semicolon just terminates the line.

share|improve this answer

From the grep man page:

   -q, --quiet, --silent
          Quiet;  do  not write anything to standard output.  Exit immedi-
          ately with zero status if any match is found, even if  an  error
          was detected.  Also see the -s or --no-messages option.

Basically this is looking to see if there is a filename containing delta and returning true if there is or false if there isn't. What it's actually doing with that truth value is anyone's guess from that little snippet you have there.

share|improve this answer

It seems like it is meant to just detect if the word 'delta' is in the list, in which case it will return 0, otherwise it will return 1. So, based on the return value, you know if delta was there or not.

share|improve this answer

The last part redirects standard output and standard error to /dev/null - I.e., any output of the grep command (errors, warnings, or matches) is dropped. This kind of command can be useful to do a simple check with no output - The $? variable will be zero or non-zero depending on whether the grep succeeded or not.

You could simplify this code by replacing > /dev/null 2>&1 with &>/dev/null, which in this case will do the same thing: Redirect all output streams to /dev/null.

See I/O Redirection for details.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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