I'm looking for a method to consistently capture the output of my last command in a variable without having to modify the command itself by adding prefixes or suffixes like 'capture' or '2>&1'. I currently use '2>&1 | tee capture.log', but it feels tedious to do it every time. Is there a simpler way to ensure that the output of the last command is always stored in an environment variable?
5 Answers
There's no clean built-in way to do this, but I came up with a somewhat hacky solution. You can define a function that captures the output of each command you run and then stores it in a variable. It uses the 'trap' command with 'DEBUG' to execute this function every time a command is run. Just keep in mind that it feels a bit clunky!
Be careful with this idea! If you run something like `yes`, you could end up crashing your system due to excessive RAM usage. You really only need to keep the latest output, but plan wisely to avoid issues with memory.
Exactly! You only want the most recent output, so it shouldn't build up in memory.
I'm having a hard time seeing the need for this. Isn't the output from your last command right there on the screen? Plus, if you're running commands and tweaking them, it might be more practical to just repeat the commands you want instead of needing the output saved in a variable.
Have you checked out the 'script' command? It allows you to create a typescript of your terminal session. This way, you don’t have to keep capturing outputs manually! Here are a couple of articles explaining it: [Red Hat Blog on script command](https://www.redhat.com/en/blog/linux-script-command) and [replay saved sessions](http://redhat.com/en/blog/playback-scriptreplay).
It's interesting that you want to keep the output all the time. Can you explain a bit more why it's necessary for you? Have you thought about simply wrapping the commands you use? If there are a lot of different commands, it might get complicated, though.
Good point, I think I’ll set up a VM and run some tests to see how it handles that.