Can I configure bash to execute “clear” before every command typed in the console?

I would like to configure bash to execute clear command every time I type some command in the terminal (before executing my command). How can I do that?

I’m using Debian Linux.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Bash has a precommand hook. Sort of.

preexec () {
  clear
}
preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return                     # do nothing if completing
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # don't cause a preexec for $PROMPT_COMMAND
    local this_command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`; # obtain the command from the history, removing the history number at the beginning
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG

Method 2

bind 'RETURN: "e[1~clear; e[4~n"'

After that every time you press return instead of just writing n it will move to the beginning of line, enter the text clear;, then move to the end and enter n as it expected.

Method 3

from a question I asked today (with credit to user @aecolley’s answer) :

bind '"C-m": "C-lC-j"'

The C-m simulating the ‘Enter’ key, the C-l simulating Ctrl+l as it’s clear and the C-j is “newline-and-indent”, so the command is binding Enter key to Ctrl+l & Ctrl+j

that works on GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin14) and the other answers on this thread do not. also, this does not pollute history with ‘clear’ commands every other command.

Method 4

Consider only clearing when you want to

cb4() {
  preexec () {
    clear
  }
}

This uses a hook called preexec, confirmed works with zsh too

Then any session you want to automatically clear before every command you run: cb4

If you are certain you always want to clear in every context

preexec () {
  clear
}

And a if you actually want to reset the terminal

replace the word clear with tput reset

tput is optional but speeds up the reset process


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x