Search code examples
linuxbashmacosapplescriptmacos-sierra

Apple Script to create a new tab to run a bash command


I'm trying to write a function to creates a tab and run a command using Apple Script.


I've tried

tell application "Terminal"
    activate
    
    my makeTab("desktop", "ls")
    
end tell

on makeTab(name, command)
    
    do shell script command
    
    tell application "System Events"
        keystroke "t" using {command down}
        delay 0.2
        keystroke "i" using {shift down, command down}
        keystroke tab
        keystroke name
        key code 53
        
    end tell
end makeTab

Result

I kept getting

sh: eCmd: command no found

enter image description here

Any hints for me on how can I make it work?


Solution

  • It's a terminalogy conflict, name and command are reserved terms of AppleScript.

    You can't use these terms as parameters of an handler.


    Check the color of these variables.

    • the color of the variables must be green.
    • Purple : it's a property or a constant
    • Blue : it's a command or a class

    So, change the name of these variables.

    If you want to run a command in the new tab, use the do script command, not do shell script, like this:

    tell application "Terminal"
        activate
        my makeTab("desktop", "ls")
    end tell
    
    on makeTab(tName, tCommand)
        tell application "System Events"
            keystroke "t" using {command down}
            delay 0.2
            keystroke "i" using {shift down, command down}
            keystroke tab
            keystroke tName
            key code 53
        end tell
        tell application "Terminal"
            do script tCommand in front window -- run the command in the new tab
        end tell
    end makeTab