A safer way to write this applescript

applescriptterminal

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.

clear(){
    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?

Best Answer

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'
}