Search code examples
applescript

Problem when removing unicode characters via do shell script, Error <text> number 1


I have a text that I wanted to simplify, by removing the unicode characters. It works fine when I run in bash, but I get a strange error when I run it in AppleScript.

set mytext to "SomeApp™ on the App Store"
log (do shell script "echo '" & mytext & "' | /usr/bin/iconv -c -s -f utf-8 -t ascii")

The reply is:

tell current application
do shell script "echo 'SomeApp™ on the App Store' | /usr/bin/iconv -c -s -f utf-8 -t ascii"
    --> error "SomeApp on the AppStore" number 1
Result:
error "SomeApp on the AppStore" number 1

Solution

  • It appears that, while the -c -s options prevent iconv from printing errors due to untranslatable characters, it'll still exit with an error status (specifically, a status of 1); AppleScript is detecting this and reporting it (that's the "number 1" part of its message). Here's an example of the same effect in the shell:

    $ echo "SomeApp™ on the App Store" | /usr/bin/iconv -c -s -f utf-8 -t ascii || echo "There was an error, status = $?"
    SomeApp on the App Store
    There was an error, status = 1
    

    You can suppress this by adding || true to the shell command, which will make the overall command succeed even if iconv "fails". Unfortunately, it'll also prevent AppleScript from detecting other -- real -- errors; I don't know a way to fix this.

    I'd also recommend using quoted form of rather than manually adding quotes around the string (which will fail completely if the string contains ASCII apostrophes). Something like this:

    set mytext to "SomeApp™ on the App Store"
    log (do shell script "echo " & (quoted form of mytext) & " | /usr/bin/iconv -c -s -f utf-8 -t ascii || true")