Sean Rahman
Sean Rahman

Reputation: 43

AWK Command returning 0

While running the AWK command with the following code

awk -F: 'BEGIN{OFS=":"} ($2 != "*" && $2 != "!") {$2=system("openssl passwd -1 -salt {salt} {password}"); print $2}' PASS/shadow.txt > PASS/test.txt |  cat PASS/test.txt 

When printing the command, I will receive:

"The salted password"
0

It will change the $2 to 0. But still print off the hash. Is there anyway to fix this and have 2 = the output of the command.

I'm trying to replace all the $2 fields with a new password hash as an example project in my class and store the outcome in a new file.

Upvotes: 0

Views: 800

Answers (2)

kvantour
kvantour

Reputation: 26591

The system command you use does not do what you expect. It returns the return code of the command you execute, not the standard output.

system(expression): Execute the command given by expression in a manner equivalent to the system() function defined in the System Interfaces volume of POSIX.1-2017 and return the exit status of the command.

You can easily see this with the following:

$ awk 'BEGIN{print system("true"), system("false")}'
0 1

Here we exectued the commands true and false (see man true and man false) for what they do.

If you want to capture the output of a command, the getline command is what you need. A detailed document on the do's and don't's of getline can be found in Ed Morton's All about getline. Also see his answer for the implementation for this OP.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204731

It sounds like this might be what you're trying to do:

awk '
    BEGIN { FS=OFS=":" }
    $2 !~ /^[*!]$/ {
        cmd = "openssl passwd -1 -salt {salt} {password}"
        if ( (cmd | getline line) > 0 ) {
            $2 = line
        }
        close(cmd)
    }
    { print }
' PASS/shadow.txt > PASS/test.txt

If not then edit your question to clarify your requirements and provide a better example.

Upvotes: 2

Related Questions