0

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.

0siris
  • 13
  • 1
  • 7
  • Knowing what you've tried would be a helpful first step in answering this. – womble May 19 '18 at 06:17
  • I apologize, I was going to put some but I had tried several different ones, and by the time I got to asking this question it wasn't fresh in my mind anymore. However for next time I will keep the code I have been trying in commented blocks so I can keep track... – 0siris May 21 '18 at 17:13

2 Answers2

0

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
Craft
  • 171
  • 1
  • 5
  • Instead of redirecting the output to a file, one could directly save the output in the variable with a command substitution `MY_VAR=$(my_command)`. – Thomas May 18 '18 at 17:11
0

The best answer for what I am trying to do is like so:

savedOuput=$(date)

This will save the output of the date command into the savedOutput variable.

'echo $savedOutput'

Will print the contents that were saved on the 'savedOutput' variable

0siris
  • 13
  • 1
  • 7
  • You should double-quote both `$(date)` and `$savedOutput`, to prevent problems with whitespace. – womble May 21 '18 at 23:28