2

So I have the following script saved as usr/local/bin/spawn which opens a process in a new terminal window, and then closes that window:

#!/bin/sh
osascript <<END
tell app "Terminal" to do script "$1; logout"
END

So I can do

$ spawn nano

to open a new terminal window with nano running, and when I close nano the window also closes.

However, to spawn a command with arguments, like java -jar foo.jar, I need to use

$ spawn "java -jar foo.jar"

Is there a way to change the script so that the same will work without the quotes? For example,

$ spawn java -jar foo.jar

I have tried using the trick from this answer to a question that doesn't deal with AppleScript. However that always caused Terminal.app to crash when I tried using spawn. Is there a way to escape the "$@" or a different implementation for this problem? It doesn't necessarily have to use AppleScript.

Community
  • 1
  • 1
Fenhl
  • 2,316
  • 2
  • 17
  • 10

2 Answers2

0
#!/bin/sh
osascript <<END
tell app "Terminal" to do script "$@; logout"
END

seems to work for me.

Another option that would solve your problem would be to save the code to be executed in a file in a temporary folder and open it with Terminal like so:

#!/bin/sh
file=$(mktemp $TMPDIR/spawnXXXXXX)
echo '#!/bin/sh' > "$file"
echo "$@" >> "$file"
chmod +x "$file"
open -a Terminal "$file"

Or if you would like to open it in your current terminal program (Terminal, iTerm 2, etc.) you could use this script:

#!/bin/sh
file=$(mktemp $TMPDIR/spawnXXXXXX.command)
echo '#!/bin/sh' > "$file"
echo "$@" >> "$file"
chmod +x "$file"
open "$file"
Tyilo
  • 28,998
  • 40
  • 113
  • 198
0

Your script isn't escaped properly either. spawn 'echo "a"' would result in an error because of the double quotes.

You can use the run handler to pass arguments to osascript:

#!/bin/bash

osascript - "$*" <<END
on run args
tell app "Terminal"
do script item 1 of args
do script "logout" in window 1
end
end
END

"$*" is like "$@" but with all arguments in a single word.

Lri
  • 26,768
  • 8
  • 84
  • 82
  • This approach kills the original Terminal window the instant the new one is spawned. – Fenhl Dec 20 '12 at 10:08
  • @Fenhl What do you mean with kill? The logout command should be run in the opened window. If you actually want to close the new window, replace `do script "logout" in window 1` with `close window 1`. – Lri Dec 20 '12 at 14:39
  • I meant closes, sorry. And I don't know a lot about AppleScript, but it looks like `window 1` refers to the window where I called the `spawn` script. – Fenhl Dec 24 '12 at 00:21