1

AppleScript has no problem dealing with UTF-8 characters inside the script. But it is unable to retrieve UTF-8 characters correctly from the environment variables.

osascript -e 'do shell script "echo " &"你好"'

你好

HELLO=你好 osascript -e 'do shell script "echo "& (system attribute "HELLO")'

你好

Any suggestions to fix this?

RobC
  • 22,977
  • 20
  • 73
  • 80
Meow
  • 4,341
  • 1
  • 18
  • 17

1 Answers1

1

Looks like system attribute doesn’t respect the shell environment’s LANG. Eh, they’re both ancient and nasty.

This will give you the right value:

HELLO=你好 osascript -e 'do shell script "echo \"$HELLO\""'
# 你好

Alternatively, use NSUserDefaults via the AppleScript-ObjC bridge. I wrote a bunch of AppleScript libraries a few years back; the File library’s environment variables command uses this approach.

foo
  • 254
  • 2
  • 3
  • This is quite limited in its usage as it only works when retrieving UTF8 characters from the environment variables if used with `do shell script`. Lets consider the following works when using `system attribute`; e.g. `HELLO=foo osascript -e 'tell app "Finder" to display dialog system attribute "HELLO"'`. However it fails when using UTF8; e.g. `HELLO=你好 osascript -e 'tell app "Finder" to display dialog system attribute "HELLO"'` _(i.e. dialog displays `‰Ω†Â•Ω`)_. So, as per this answer, the following doesn't work: `HELLO=你好 osascript -e 'tell app "Finder" to display dialog \"$HELLO\"'` – RobC Apr 29 '18 at 12:16
  • However, you can set the result of `echo` in the `do shell script` to an AppleScript variable before using elsewhere in subsequent `osascript` commands. For example, the following correctly displays `你好` in the dialog: `HELLO=你好 osascript -e 'set envVar to do shell script "echo \"$HELLO\""' -e 'tell app "Finder" to display dialog envVar'` – RobC Apr 30 '18 at 09:46