0

I am getting all the lines as output. The if condition of the following code is not working.

grep -Ev '^(halt|sync|shutdown)' /etc/passwd | awk -F: '{\
    if("$7"!="$(which nologin)") \
        { print $0; } \
    }'

I tried with different if conditions:

This is also returning all the values.

if("$1"!="usbmux") \
        { print $1; } \

But this is not returning anything even though there is one usbmux entry in $1.

if("$1"=="usbmux") \
        { print $1; } \
  • 1
    Welcome to the site. As a general note, it is rarely necessary to use combinations of grep and awk in a piped command; usually, awk is capable of doing everything by itself, and using only one program can help prevent a lot of mistakes (I've had my share of experience with that ;) ). – AdminBee Mar 06 '20 at 09:01
  • You probably want to read the first 40 pages of the "GNU Awk User's Guide", especially the excellent examples. – Paul_Pedant Mar 06 '20 at 10:34

1 Answers1

0

In awk, don't quote variables.

awk -F : '$1 == "usbmux"'

This would print all lines whose first :-delimited field is exactly the string usbmux. The default action is to print the current record (line, by default) if no explicit action is associated with a condition.

awk -F : -v string="$( command -v nologin )" '$7 == string'

This would print all lines whose 7th :-delimited field is the path to the nologin utility. The awk variable string is set to the output of command -v nologin on the command line with -v.

awk -F : -v string="$( command -v nologin )" '$1 !~ /^(halt|sync|shutdown)$/ && $7 == string'

This does the same as the command above it, but it avoids the lines whose first field is one of halt, sync or shutdown (without using grep).

I used command -v nologin to get the path of the nologin utility rather than which, see "Why not use "which"? What to use then?" for why.

Kusalananda
  • 333,661