在新的Mac OS X终端窗口中运行命令

Wal*_*t D 85 macos bash terminal

我一直试图弄清楚如何在新的Max OS X Terminal.app窗口中运行bash命令.举个例子,这是我在新的bash过程中运行命令的方法:

bash -c "my command here"
Run Code Online (Sandbox Code Playgroud)

但是,这会重用现有的终端窗口而不是创建新的终端窗口.我想要的东西:

Terminal.app -c "my command here"
Run Code Online (Sandbox Code Playgroud)

但当然这不起作用.我知道"open -a Terminal.app"命令,但是我没有看到如何将参数转发到终端,或者即使我使用了什么参数.

cob*_*bal 87

我能想到的一种方法就是创建一个.command文件并像这样运行它:

echo echo hello > sayhi.command; chmod +x sayhi.command; open sayhi.command
Run Code Online (Sandbox Code Playgroud)

或使用applescript:

osascript -e 'tell application "Terminal" to do script "echo hello"'
Run Code Online (Sandbox Code Playgroud)

虽然你要么必须逃避很多双引号,要么不能使用单引号

  • 如果该命令需要参数化运行,则可能需要交换单引号和双引号。尽管您需要了解差异才能正确执行此操作。osascript -e“告诉应用程序\” Terminal \“做脚本\” echo'$ variable'\“'`` (2认同)

0sc*_*car 63

部分解决方案:

把你想要的东西放在shell脚本中,就像这样

#!/bin/bash
ls
echo "yey!"
Run Code Online (Sandbox Code Playgroud)

并且不要忘记' chmod +x file'使其可执行.然后你可以

open -a Terminal.app scriptfile
Run Code Online (Sandbox Code Playgroud)

它将在一个新窗口中运行.bash在脚本末尾添加' '以防止新会话退出.(虽然您可能必须弄清楚如何加载用户rc文件和东西..)

  • 新打开的窗口的上下文似乎是用户的根文件夹`/ Users/{username}`.有没有办法让上下文文件夹与打开它的父终端窗口保持一致? (5认同)

小智 32

我一直试图这样做.这是一个更改到同一工作目录的脚本,运行命令并关闭终端窗口.

#!/bin/sh 
osascript <<END 
tell application "Terminal"
    do script "cd \"`pwd`\";$1;exit"
end tell
END
Run Code Online (Sandbox Code Playgroud)


Al *_*hou 8

如果有人关心,这里是iTerm的等价物:

#!/bin/sh
osascript <<END
tell application "iTerm"
 tell the first terminal
  launch session "Default Session"
  tell the last session
   write text "cd \"`pwd`\";$1;exit"
  end tell
 end tell
end tell
END
Run Code Online (Sandbox Code Playgroud)


小智 5

这是另一种做法(也使用 AppleScript):

function newincmd() { 
   declare args 
   # escape single & double quotes 
   args="${@//\'/\'}" 
   args="${args//\"/\\\"}" 
   printf "%s" "${args}" | /usr/bin/pbcopy 
   #printf "%q" "${args}" | /usr/bin/pbcopy 
   /usr/bin/open -a Terminal 
   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "/usr/bin/clear; eval \"$(/usr/bin/pbpaste)\""' 
   return 0 
} 

newincmd ls 

newincmd echo "hello \" world" 
newincmd echo $'hello \' world' 
Run Code Online (Sandbox Code Playgroud)

请参阅:codesnippets.joyent.com/posts/show/1516