Home > other >  I need help understanding a awk Linux Command
I need help understanding a awk Linux Command

Time:04-27

What does awk -F: '!($3 < 512 && $4 < 30)' /etc/passwd do in Linux? I only find awk is a scripting language but cant understand all this is doing.

CodePudding user response:

The awk world is based on the pattern condition{action} and this is applied to every single input record/input line of the input file.

If {action} is missing the default action is executed = print which actually means print $0
if (condition) is missing the default condition true is used

-F: Adjust the field delimiter to be : instead of [[space]] that is the default field delimiter of awk. Field delimiter in awk can be almost anything , including regex and logical (i.e or) expressions.

$3 , $4 The 3rd and 4th field of the input line (delimited by : in your code)

($3 < 512 && $4 < 30) Is a condition , && is AND operator.

! in front of the condition is just a NOT operator, to reverse the logic of the (condition)

More interesting options of awk:

$0 : is the whole input line read from file, not splitted
$NF : is the last field of the input line
NF : is the number of fields
RS : The input record/line separator can be adjusted not to be \n (awk's default)
ORS : output record separator (default of awk is \n)
Try : echo "one two three" | awk '{print $2}'
echo "one two three" |awk '1' RS=" " ORS="\n"

And a lot of more info about awk can be found either in man awk and info awk or in the official awk documentation i.e https://www.gnu.org/software/gawk/manual/gawk.html for gnu awk - gawk

CodePudding user response:

This is shorthand for

awk -F: '!($3 < 512 && $4 < 30) { print; }' /etc/passwd

and means "show all lines where NOT (:-separated field #3 is less than 512 and field #4 is less than 30)" from /etc/passwd

With the help of man 5 passwd and DeMorgan's law, this corresponds to "show the user account list where the user id is greater than 512 or the group id is greater than 30".

This logic is likely intended to only show human users on the system, since a common convention is to assign them higher UIDs than non-human, system users like apache and mysql.

  • Related