Search code examples
bashterminalapplescriptprofile

AppleScript - send a message to the terminal window a bash script is running in, even when that window does not have focus


Update: cloned to here: https://apple.stackexchange.com/q/460841/209336


I'd like to have a bash script along the lines of this:

# set terminal window profile to profile2
sleep 300
# set terminal window profile to profile1

during that sleep, I might go off and start using a different application than Terminal, or I might be using a different Window of Terminal. So the approaches which send a message to the active or front terminal window don't work. Can I grab the current terminal window ID at the start and re-use it later ?


Solution

  • You can use tty to identify the window.

    Save following script to test.sh and run it with bash test.sh

    #!/usr/bin/env bash
    
    osascript -e 'tell application "Terminal" to set current settings of (the first window whose tty of tab 1 contains "'"$(tty)"'") to settings set "Basic"'
    
    echo "You can switch to another windows"
    
    sleep 6
    
    osascript -e 'tell application "Terminal" to set current settings of (the first window whose tty of tab 1 contains "'"$(tty)"'") to settings set "Grass"'
    

    Update

    Sonoma version :

    #!/usr/bin/env bash
    
    FUNCTION='
    on findTTYWindow(input_tty)
        tell application "Terminal"
            set theWindows to every window of it
            repeat with theWindow in theWindows
                if tty of tab 1 of theWindow contains input_tty then
                    return theWindow
                end if
            end repeat
        end tell
    end findTTYWindow'
    
    osascript -e 'tell application "Terminal" to set current settings of my findTTYWindow("'"$(tty)"'") to settings set "Basic"'"$FUNCTION"
        
    echo "You can switch to another windows"
            
    sleep 6     
                    
    osascript -e 'tell application "Terminal" to set current settings of my findTTYWindow("'"$(tty)"'") to settings set "Grass"'"$FUNCTION"