3

I want to do this in 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

Only the last line is executed.

However, if I do just:

osascript -e "\"$script\""

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

You can see all the lines are there.

How do I fix this?

Tyilo
  • 28,998
  • 40
  • 113
  • 198
  • 1
    Please edit your script to include example output, especially for `osascript -e "\"$script\""`. It is really hard to tell what you **are** seeing and what you **expect** to see. Good luck. – shellter Aug 04 '11 at 03:46
  • Is this the same problem as described in http://stackoverflow.com/questions/274469/cant-do-shell-script-with-a-repeat-with-i-from-1-to-n-loop ? – nekomatic Aug 04 '11 at 07:27

2 Answers2

4

Just add without altering line endings (though this will add a trailing newline character).

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.
# ...
jon
  • 56
  • 1
0

You may have to print the entire command string to a temporary file and then calling osascript on the file instead of trying to fit a multiline value into a single line.

Femi
  • 64,273
  • 8
  • 118
  • 148
  • One thing to note is that the `osascript` expects to accept multiple `-e` arguments, with each one being a separate line: this may be the source of the problem. Try switching quotes around? Perhaps `osascript -e 'do shell script \"$script\" with administrator privileges'` might work? – Femi Aug 04 '11 at 06:30