I sometimes use a third party application with a built in terminal when writing and/or testing a script. I wrote this short applescript to fully clear the terminal screen regardless of which application I'm using. I set it as a function at the top of some of my scripts. I never had a problem until earlier today when I carelessly ran this in a while true loop.

    osascript -e \
    'set theApp to (get the path to the frontmost application) as text
    set this_app to the name of application theApp
    activate application this_app
    tell application "System Events" to keystroke "k" using command down'   

Obviously running this endlessly is not a good thing. I was forced to manually power off the computer because it was stuck in the frontmost application hitting cmd k endlessly. Is there a better way to write this so this doesn't happen again?

  • There is nothing wrong with the function per se, Just don't call it in an endless loop! That said, personally I'd rather type ⌘K, two keystrokes vs. clear five keystrokes, as it just seems senseless to type five keystrokes when 2 is all that required! If I was going to use it I call it c, then it's on one keystroke! :) Isn't that the whole point of using computers... input less, output more. :) Mar 19, 2017 at 2:08
  • Lol fair enough. The name is just so I don't forget what it does. It's more about automation than number of keystrokes but I see what you're saying. Good point.
    – I0_ol
    Mar 19, 2017 at 2:38
  • Why not just type ctrl+l in the terminal
    – mmmmmm
    Mar 19, 2017 at 22:20
  • @Mark ctrl+l clear the screen but still allows you to scroll up to see what was on the screen beyond what was just cleared. ⌘K clears the screen entirely.
    – I0_ol
    Mar 20, 2017 at 4:50

1 Answer 1


A much safer way is just to action the menu directly.

clear() { osascript \
  -e 'tell application "System Events" to tell process "Terminal"' \
  -e   'click menu item "Clear to Start" of menu 1 of menu bar item "Edit" of menu bar 1' \
  -e 'end tell' \
  -e 'return'
  • Your code as written... 1. Only works for OS X El Capitan and later, it's "Clear All" prior to OS X El Capitan. 2. It only works in Terminal and the OP expressed he wants to use the same thing in Terminal and another app that has a built in terminal, with apparently has the same ⌘K keyboard shortcut, so this will not work in the OP's scenario on at least #2 as his code does. Don't know which OS he's running for the menu command which is why keystroking ⌘K may be better for him. Mar 19, 2017 at 23:11
  • @user The code is an example. My first sentence is my real answer, but I thought it might be helpful to provide a code example. Of course, OP can edit the code to do whatever they wish, this is just a starting point for how to manipulate menus directly, which was the purpose of my answer.
    – grg
    Mar 20, 2017 at 10:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .