Bash是否具备类似Octave的diary启停日志记录功能?
diary Command Great question! I totally get why Octave's diary command is such a lifesaver—being able to toggle session output logging on and off is perfect for debugging, especially when you're wrangling large datasets and can't afford to miss any critical output. Let's walk through the best Bash equivalents that match that start/stop functionality, way better than manual echo >> appends.
1. The script Command: Your Direct Octave diary Equivalent
This is the closest thing Bash has to Octave's diary—it's built-in, dead simple, and made specifically to record terminal sessions (or parts of them).
- Start logging: Run
script my_bash_diary.login your terminal. From this point on, all your commands and their output (both stdout and stderr) will be saved tomy_bash_diary.log. - Stop logging: Just type
exitor pressCtrl+D—recording stops immediately, and you’re back to your regular terminal prompt. - Bonus features:
- Append to an existing log instead of overwriting it:
script -a my_bash_diary.log - Start logging silently (no "Script started..." message cluttering your log):
script -q my_bash_diary.log
- Append to an existing log instead of overwriting it:
This is my go-to tool for quick session logging—it requires zero setup and behaves exactly like you’d expect diary to.
2. Custom Toggleable Logging with Redirection & Traps
If you need more control (like starting/stopping logging mid-session without ending your shell), you can set up a custom function using shell redirection and traps. Here’s a straightforward implementation:
# Define your log file path LOGFILE="custom_bash_diary.log" # Function to start logging start_log() { # Redirect stdout and stderr to both the terminal and the log file exec > >(tee -a "$LOGFILE") 2>&1 echo "Logging started. Output will be saved to $LOGFILE" } # Function to stop logging stop_log() { # Close the redirected file descriptors exec >&- 2>&- # Restore output to the original terminal exec >/dev/tty 2>&1 echo "Logging stopped. Check $LOGFILE for your session output" }
- Use it: Just type
start_logto begin recording, andstop_logto pause. You can toggle this as many times as you want during your session. - How it works: The
teecommand ensures you still see output in your terminal while saving it to the log, andexecredirects the shell’s standard output/error permanently until you restore it withstop_log.
Why Manual echo Appends Aren’t Ideal
While echo "some output" >> diary.txt works for single lines, it’s tedious if you want to log multiple commands or entire blocks of output. The methods above automate the process so you don’t have to manually redirect every single command you run.
内容的提问来源于stack exchange,提问作者Script Kitty

