I want a similar behavior as
nano etc. uses.
Is this possible to achieve with bash?
If your terminal emulator supports it, you can do this using the same mechanism used by
vim, et al, namely the
te termcap capabilities (
rmcup in the more modern terminfo). These switch from the primary to the secondary screen, and back to the primary, respectively.
If your system has the
tput command, you can use:
tput smcup # switch to secondary screen ... tput rmcup # switch back to primary screen
xterm, and probably for most other terminal emulators, this:
should switch to the secondary screen, and this:
should switch back to the primary (and put the cursor back where it was).
tcsh has a built-in
echotc command, so you could do:
tcsh -c 'echotc ti' ... tcsh -c 'echotc te'
(or just use
echotc directly if you happen to be using tcsh).
This is called the “alternate screen” (and as the top google hits show, you are unusual in liking this feature). Some terminals support two screen buffers, one used by full-screen applications, the other used by line-oriented applications. Bash doesn't know anything about them. If a command simply emits output to the terminal, you can use terminal control sequences to switch to the secondary screen and back (these commands are documented in xterm ctlseqs).
printf '\e[?47h'; mycommand; printf '\e[?47l'
Note that there is no scrollback for the alternate screen, so you'll only see the last screenful of output. If that's a problem, just do the simple thing:
mycommand | less
Bash knows nothing about screens (it can run without being seen, in fact). You can redirect both standard output and standard error to any file or pipe, though.
None of the current answers seemed to work on my machine, but I found out about the command named
screen, which seems to do the trick for me.