Search code examples
iterm2iterm

How to programmatically clear the iterm2 buffer?


When I search with iterm2, using ctrl+f, it will search through older stuff in the buffer, older than the current process I am running in the terminal. In this case I don't care about the older stuff in the buffer, I want to delete it.

My question is - is there a way to programmatically clear the buffer, using a bash script/command? I could call this shell command from my process when it starts up.


Solution

  • You can use AppleScript to clear the scroll back buffer and then do a terminal clear, drop the following into a bash script (or compile just the AppleScript part and run it via osascript)

    Note: Trying to do just a "Clear Buffer" will not work as the cmd is actually still running and iTerm accept the CMD-K, but it does not clear the screen... bug? execution timing? ....

    #!/bin/bash
    read -r -d '' script <<'EOF'
    on run argv
       tell application "iTerm"
         tell application "System Events" to keystroke "K" using {shift down, command down}
         tell current window
            tell current session
               write text "clear"
            end tell
         end tell
       end tell
    end run
    EOF
    echo "$script" | osascript ``-'' $@