Search code examples
macosapplescriptosx-mavericks

Display dialog if a word isn't on a list applescript


I'm writing a script that can open and close apps for me. Basically, I type in an app name, and then it opens the app. The only thing is, if the app isn't found, it throws an error and quits. I want to make the script just display a dialog that says something like "App not found".

Here's what I have so far:

if userInput contains "Activate " then set {TID, text item delimiters} to {text item delimiters, {"Activate "}}
if length of userInput is less than or equal to 1 then say (resultString as string)
if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
set openApp to (resultString as string)
if userInput contains "Activate " then set text item delimiters to TID
if userInput contains "Activate " then tell application (openApp as string) to activate

BTW, this is just a snippet of my script, which is why there are some undefined variables here.

I tried:

set appList to do shell script "cd /Applications; ls"
if openApp is not in appList then display dialog "App not found"

Huh, Applescript syntax can be so annoying sometimes.

Thanks.


Solution

  • There's exists application but that would also popup a dialog asking "Where is xyz?".

    So the best thing you can do seems to be:

    tell application "Finder" to set appExists to (exists file myApp of folder "Applications" of startup disk)
    
    if not appExists then
        display alert "App not found"
    end if
    

    Your code is then:

    if userInput contains "Activate " then set {TID, text item delimiters} to {text item delimiters, {"Activate "}}
    if length of userInput is less than or equal to 1 then say (resultString as string)
    if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
    set openApp to (resultString as string)
    
    if userInput contains "Activate " then set text item delimiters to TID
    
    tell application "Finder" to set appExists to (exists file (openApp & ".app") of folder "Applications" of startup disk)
    if not appExists then
        display alert "App not found"
    else
        if userInput contains "Activate " then tell application (openApp as string) to activate
    end if
    

    Or try to catch the error if the user presses Cancel:

    try
        if userInput contains "Activate " then tell application (openApp as string) to activate
    on error
        display alert "App not found"
    end try