osascript中的多行字符串

时间:2011-08-04 03:38:07

标签: bash applescript osascript

我想在bash中这样做:

read -r -d '' script <<'EOF'
echo 1
echo 2
echo 3
EOF

osascript -e "do shell script \"$script\" with administrator privileges"

# Output: 3
# Expected: 1
# 2
# 3

只执行最后一行。

但是,如果我这样做:

osascript -e "\"$script\""

# Output: echo 1
# echo 2
# echo 3
# Expected: echo 1
# echo 2
# echo 3

你可以看到所有的线都在那里。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

只需添加without altering line endings(虽然这会添加一个尾随的换行符)。

read -r -d '' script <<'EOF'
echo 1
echo 2
echo 3
EOF

osascript -e "do shell script \"$script\" with administrator privileges without altering line endings" | sed '$d'


# See:
# "do shell script in AppleScript",
# http://developer.apple.com/library/mac/#technotes/tn2065/_index.html
# ...
# By default, do shell script transforms all the line endings in the result to 
# Mac-style carriage returns ("\r" or ASCII character 13), and removes a single 
# trailing line ending, if one exists. This means, for example, that the result
# of do shell script \"echo foo; echo bar\" is \"foo\\rbar\", not the 
# \"foo\\nbar\\n\" that echo actually returned. You can suppress both of 
# these behaviors by adding the "without altering line endings" parameter. For 
# dealing with non-ASCII data, see Dealing with Text.
# ...

答案 1 :(得分:0)

您可能必须将整个命令字符串打印到临时文件,然后在文件上调用osascript,而不是尝试将多行值插入单行。