Bash – How to Save Last Line Output from Terminal in Bash Script

bashscriptingshellshell-scripting

I am writing a bash script in which I would like to save the output of the last command in to a variable before running my next one so I can display it later.

I have tried a few different methods using tail with no success.

Any help will be very appreciated.

Best Answer

You can save the output of your last command to a temporary file, using tee.

TMPPFILE=$( mktemp );
echo "First command" | tee ${TMPFILE};
echo "Second command" | tee ${TMPFILE};
echo "Third command" | tee ${TMPFILE}

Then:

cat ${TMPFILE}     ## Should produces the line below
Third command