3

我想在 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

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

我该如何解决?

4

2 回答 2

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.
# ...
于 2011-08-04T11:58:29.503 回答
0

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

于 2011-08-04T04:08:26.507 回答