AWK syntax

Hi I am trying to understand AWK syntax
so I tried this command which gives me the home directory of root

awk 'BEGIN { FS = ":"} {if ($1 == "root") print $6 }' /etc/passwd

I would know what are the following commands doing. The first one prints all /etc/passwd, second prints nothing.

awk 'FS = ":"; {if ($1 == "root") print $6 }' /etc/passwd
awk '{FS = ":"; if ($1 == "root") print $6 }' /etc/passwd

What are the differences between those three commands? I know about awk that in BEGIN I put code that is executed once before processing rows. and END is executing at the end of processing all rows.

also this command work as expected but it is just different form of first

awk -F ':' '{if ($1 == "root") print $6 }' /etc/passwd

Thanks a lot

In number 2 'FS = ":"' means if the assignment of ":" to the variable FS is successful, print the whole record. In both number 2 and 3 FS is assigned this value again and again for every record, but at that point my guess is it is too late as the fields will already have been split using the default field separator. Therefore $1 will never equal root.

and code behind ';' is never executed ???
and why do you mean it is too late ? i declaret it before it porcess row. If I am wrong correct me

The code behind the ; is executed. An clearer equivalent to the

FS = ":";

is

FS = ":" { print }

So every line is printed. The next bit gets executed but will never match successfully.

That's because the input string has already been processed into fields using the default FS. When your FS assignment is executed for the first line of the file, it will not change the fields of the already read first line (which is usually root) of the password file.

Indeed it is never executed (well the if statement is evaluated it just never evaluates to true) because the first time the fields are not split on ":" and root is the first entry in the password file. Either that or the fields never get split on ":" for the remaining entries either. Anyway, FS should be set in the BEGIN section or as -F on the command line and not in the main loop.