LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Opposite to expected response in awk (https://www.linuxquestions.org/questions/linux-general-1/opposite-to-expected-response-in-awk-4175561013/)

rng 12-08-2015 10:06 PM

Opposite to expected response in awk
 
I am using following awk code on a file called dirlist. However, it is giving reverse response- printing out directories if they are there when asked about not there and vice versa:

Code:

$ cat dirlist
/root
/boot
/sys
/a_dir
/b_dir

# TRYING TO PRINT IF DIRECTORY IS PRESENT:
$ cat dirlist | awk ' { if ( system(" [ -d " $1 " ] ")  ) print $1 } '
/a_dir
/b_dir

# TRYING TO PRINT IF DIRECTORY IS ABSENT:
$ cat dirlist | awk ' { if ( system(" [ ! -d " $1 " ] ")  ) print $1 } '
/root
/boot
/sys

Where is the problem. Thanks for your insight.

berndbausch 12-08-2015 11:33 PM

system() returns the command's exit status. "[ -d a_dir ]" has an exit status of 0 when a_dir exists, and 1 when it doesn't exist.

Now when the if condition is nonzero, awk considers it as true. So, a nonexisting directory returns 1, which is true.

rng 12-09-2015 01:45 AM

Perfect explanation.


All times are GMT -5. The time now is 03:57 PM.