user3414803
user3414803

Reputation: 1

AppleScript triggered on a certain terminal output

I have an AppleScript written that tells terminal to do a script.

on run

    tell application "Terminal"
        set currentTab to do script ("...")
    end tell


end run

However I want to trigger it to run only when I get certain output from a terminal window.

What is the best way to do it?

I tried:

 tell application "Terminal"

        if contents of front window contains "..." then
            say "match"

        else
            say "no match"
        end if

end tell

however it doesn't seem to work. Would method would you suggest to use?

Upvotes: 0

Views: 1469

Answers (2)

DrLulz
DrLulz

Reputation: 146

Without creating an application, you need to write the terminal output to a .txt or log file and then read it.

So, to define the txt file:

set temp_file to quoted form of (POSIX path of (path to temporary items from user domain) & "logger.txt")

then create the text file and write terminal output:

try
    do shell script "rm -f " & temp_file
end try
do shell script "touch " & temp_file
do shell script "do something " & " | tee " & temp_file

get Applescript to read the file and turn each line into a list item:

set the_output to my get_lines()
on get_lines()

    set temp_file to (POSIX path of (path to temporary items from user domain) & "logger.txt")
    set logs to paragraphs of (read temp_file)
    set line_count to count of logs

    set line_items to {}
    repeat with i from 1 to line_count by 1
        if (i + 0) is not greater than line_count then
            set end of line_items to items i thru (i + 0) of logs
        else
            set end of line_items to items i thru line_count of logs
        end if
    end repeat

    return line_items

end get_lines

Find your "certain output" and pull the trigger...

repeat with n from 1 to (count of the_output)

    set str to text of (item n of the_output) as string

    if str starts with "TEXT TO LOOK FOR" then

        do something

    end if

end repeat

Upvotes: 1

Darrick Herwehe
Darrick Herwehe

Reputation: 3742

Your script is only running through once, then quitting. You need to create a stay open script with an idle handler that periodically checks the Terminal contents.

For example:

on idle
    tell me to run
    return 5 * minutes --Runs the script every 5 minutes
end idle

When you save your file, select Application as the file type, and check the Stay open after run handler option. Then run your script by double clicking on the icon. The script will stay open, running every 5 minutes until you quit it.

Upvotes: 0

Related Questions