How to get execution to continue past a failing “do shell script”?

I’m writing a small application in XCode, but I usually work in Script Editor. This time I need a richer UI than is offered by the Standard Additions OSAX.

I need to use ‘do shell script’, and sometimes it will fail, so I need to get its result so I can tell the user what they did wrong. I have the following:

set theCommand to <whatever>
set theResult to (do shell script theCommand)
display alert "123"

But I’m not getting to the dialog box.

How do I obtain the result of ‘do shell script’ and continue execution with the next line of code?

Would adding the following be of use?

   set theCommand to <whatever>
   try
      set theResult to (do shell script theCommand)
   on error
      display alert "123"
   end try

Most simplest answer: add true command behind every do shell script you execute.

The following command return an error:

do shell script "false"

By adding true command at the end of the script the error is silenced:

do shell script "false;true"

This is the quick solution but not the correct one.

The error handling of a do shell script is a poor representation of what really happens. A do shell script will throw an error if the last command of the script returns a non-zero value. However a non-zero value is in a lot of cases not an error. Shell scripts should handle the return values of the command but it’s something we rarely see on MS. You can use and (&&) and or (||) operators in the shell for make it work or create an if-then statement in the shell script:

Handling command return value with if-else block:

do shell script "if [[ -d /Users/SkiAddict1 ]]
then
echo yes
else echo no
fi"

Handling return value using operators

do shell script "[[ -d /Users/SkiAddict1 ]] && echo yes || echo no"

The commands above tests if the path /Users/SkiAddict1 exists or not and if it’s an directory. By default when built-in tests fails it will throw a non-zero value which results in an error by do shell script. With the examples above the shell script reacts to the return value of the shell command and writes a value to stdout which will be returned by do shell script to the script without any errors in AS.

Utterly brilliant! Thank you so much :slight_smile: Final handler follows:

   set succeeded to true -- assume good, and adjust in error block if necessary
        try
            do shell script theCommand
        on error
            display alert "nope, try again"
            set succeeded to false
        end try
        if (succeeded) then
            quit
        end if

Many thanks for this very comprehensive answer DJ Bazzie Wazzie (and I love the handle! :wink: but the earlier solution is simpler and fits my needs perfectly.