Search code examples
bashmacosawkprintingmacos-sierra

Awk printing only strings before variables and strings


I'm trying to turn data from the last command into epoch time using the awk print. the code works on 10.14.5 all the time, and works on 10.13.6 some of the time. When I came into work this morning it worked fine, then around 11 started giving me errors.

Basically, awk is printing literal strings, then a newline character, then the literal strings and the variables as it should. for example, if $1="Hello", then:

awk '{print $1,"World"}'

is actually printing "World Hello World"

the actual line of code giving the error is this:

x=$(last -1 $a | awk '{print $3 " "$4 " " $5  " " $6 ":00 EDT "}')

where it should be setting x to "Fri May 31 12:43:00 EDT " for example, it is setting x to " :00 EDT Fri May 31 12:43:00 EDT "

EDIT: I should say that the $a in the line of code would be set to a username on the computer


Solution

  • On my High Sierra system, last -1 barmar doesn't print any useful information. My Mac has been up for 9 days (since I installed the most recent security update). It takes 8 seconds to run, and just prints:

    
    wtmp begins Fri May 31 12:53 
    

    So there's a blank line and then the line saying where wtmp begins, which always seems to be the current time.

    So the awk script is working correctly. The first line doesn't have any fields, so all the $n values will be empty, and you get just :00 EDT. The second line contains the wtmp begins line, and that creates Fri May 31 12:48:00 EDT in the output (even though you used -1, it still produces two lines of output). When you combine them, you get

    $ echo "$x"
       :00 EDT 
    Fri May 31 12:48:00 EDT 
    

    Terminal 'last' command doesn't display login history claims that sudo last should work, but it doesn't for me.

    How do you stop wtmp from erasing? suggests getting the information you want from /var/log/monthly.out.