如何编写具备vim/nano/htop特性的Shell脚本:运行后返回原终端提示符并保留历史输出
Great question! The behavior you're after—where your script runs in a "clean" screen and returns you to your original terminal state (with all previous commands/output intact) when it exits—is powered by terminal alternate screen buffers. This is exactly what tools like htop, vim, and bashtop use, and it's way simpler than relying on tmux.
Here's the breakdown of how it works:
Most modern terminals (xterm, gnome-terminal, kitty, iTerm2, etc.) come with two screen buffers:
- The main buffer: This is your regular terminal session, where you run commands and see their output history.
- The alternate buffer: A temporary, blank buffer that programs can switch to. When you exit the program, the terminal switches back to the main buffer, restoring your original session state seamlessly.
Implementing this in your script
You can control these buffers using the tput command (part of the preinstalled ncurses package on most Linux/Unix systems). Here's how to modify your example.sh to get the desired behavior:
#!/bin/bash # Switch to the alternate screen buffer when the script starts tput smcup # Define a cleanup function to switch back to the main buffer cleanup() { tput rmcup } # Trap exit signals to ensure cleanup runs no matter how we exit # (EXIT = normal exit, INT = Ctrl+C, TERM = kill command) trap cleanup EXIT INT TERM x=0 while true do x=$(expr $x + 1) clear # Keep the alternate buffer clean printf "\n\n $x"|figlet -f block sleep 1; done
Let's walk through the key parts:
tput smcup: This command tells the terminal to switch to the alternate buffer. Your current terminal state (prompt, command history, output) is saved in the background instantly.trap cleanup EXIT INT TERM: This ensures thecleanupfunction runs whenever the script exits—whether you hit Ctrl+C, usekillto stop it, or the script ends normally. No more leaving your terminal in a messy state!tput rmcup: This switches back to the main buffer, restoring your original terminal state exactly as it was before running the script.
Why this is better than tmux
Unlike running in a tmux session, this method uses the terminal's built-in functionality—no extra tools or sessions needed. It's lightweight and behaves exactly like the tools you're emulating.
A note on bashtop's source
Bashtop uses the ncurses library under the hood, which handles the alternate buffer automatically when you initialize a curses session. The tput commands we're using are just direct calls to the same terminal control sequences that ncurses uses. If you dig deeper into bashtop's code, you'd see it initializes a curses window, which triggers the smcup sequence implicitly.
内容的提问来源于stack exchange,提问作者ANDuser

