In general, command | tail -n 1
prints the last line of the output from command
. However, where command
is of the form awk '... { ... print something }'
you can refactor to awk '... { ... result = something } END { print result }'
to avoid spawning a separate process just to discard the other output. (Conversely, you can replace awk '/condition/ { print something }' | head -n 1
with awk '/condition/ { print something; exit }'
.)
If you already have the result in a shell variable s3
and want to print just the last line, a parameter expansion echo "${s3##*$'\n'}"
does that. The C-style string $'\n'
to represent a newline is a Bash extension, and the parameter expansion operator ##
to remove the longest matching prefix isn't entirely portable either, so you should make sure the shebang line says #!/bin/bash
, not #!/bin/sh
Notice also that $s3
without quotes is an error unless you specifically require the shell to perform whitespace tokenization and wildcard expansion on the value. You should basically always use double quotes around variables except in a couple of very specific scenarios.
Your Awk command would not work for two reasons; firstly, as explained in the previous paragraph, you are setting s3
to the first token of the variable, and the second is your Awk script (probably a syntax error). In more detail, you are basically running
awk -v s3=firstvalue secondvalue thirdvalue '{ print $(NF) }'
^ value ^ script to run ^ names of files ...
where you probably wanted to say
awk -v s3=$'firstvalue\nsecondvalue\nthirdvalue' '{ print $(NF) }'
But even with quoting, your script would set v
to something but then tell Awk to (ignore the variable and) process standard input, which on the command line leaves it reading from your terminal. A fixed script might look like
awk 'END { print }' <<<"$s3"
which passes the variable as standard input to Awk, which prints the last line. The <<<value
"here string" syntax is also a Bash extension, and not portable to POSIX sh
.