greenou737
greenou737

Reputation: 1

Is there a way to store lines output by last command in Bash?

I'm trying to filter and record information from the last command using a Bash script. I was wondering if there is any way to store the lines from the last command as a variable (like an array) so that they can be filtered and edited.

My first thought was trying varname=(`last`) to try and just record the information directly into a new variable, but this only records for the characters up to a space of a single line, and records it as a single string. Is there some way to record all of the lines from last as an array or other variable?

For reference, each line of last is formatted as tabulated data. An example line looks like:

abc0123 pts/01 127.0.0.1 Sat Oct 3 20:54 still logged in

or

abc0123 pts/01 127.0.0.1 Sat Oct 3 20:53 - 20:54 (00:01)

Upvotes: 0

Views: 75

Answers (1)

Martin Väth
Martin Väth

Reputation: 236

If you want a separate array entry for every line, set IFS temporarily to the newline symbol for the assignment.

IFS='
' A=(`printf 'a b\nc d'`)
echo "Line 0: ${A[0]}"
echo "Line 1: ${A[1]}"

will output

Line 0: a b
Line 1: c d

If instead you want everything as a single variable, you do not need any bashisms:

variable="`printf 'a b\nc d'`"
echo "$variable"

will output

a b
c d

Note that the latter removes possible spaces at the end of the last line. If you want to avoid that, you need a trick:

variable="`cmd; echo A`"
variable=${variable%A}

Upvotes: 1

Related Questions