从Mac Automator运行Shell脚本

14

在OS X 10.9.5中

我用vim编写了一个Shell脚本。保存后,进入该脚本并执行 sh code.sh,在iTerm和Total Terminal中都能够完美运行。

但是在同一目录下使用Mac Automator始终会产生一个错误。为什么?

在Automator和Terminal中都执行如下命令:

echo $SHELL /bin/bash

为什么通过Automator无法运行shell脚本?enter image description here


对我来说可以。code.sh 期望从某个地方输入一些内容吗?你能用 sh -x(或者更确切地说,如果它真的是一个 Bash 脚本,用 bash -x)运行它,看看它在哪里失败了吗? - tripleee
这个文件是否有尾随的换行符?对我来说,它并没有打印任何东西,但是成功了;但是我有一个不同版本的OSX用于测试(一些非常古老的版本)。 - tripleee
“Gestoppt”听起来不像是一个正确的错误,你是在大约30秒后手动停止它的吗? - tripleee
“Gestoppt”在德语中的意思是“STOP”。它不是通常的can't find lib-x or lib-y问题,而是直接终止程序运行。该Shell脚本内含一个RScriptRscript -e 'shiny::runApp(("/Users/Einstein/Git/RShiny/fooapp"),launch.browser=TRUE)' - Teletubbi-OS X
好的,是的,如果我在运行命令时加入 sleep 1000,并在允许其运行一段时间后按下停止按钮,我会得到基本相同的消息(虽然不是德语)。所以我猜这也是你所做的。 - tripleee
显示剩余5条评论
3个回答

13

这个问题可以通过在您当前的代码上方添加以下代码来解决:

export PATH=/usr/local/bin:$PATH

4
我怀疑问题在于cd Desktop这一部分。你可以尝试:
(cd ~/Desktop; sh code.sh)

然而:
  • You should make code.sh executable so you don't need to invoke it with sh. This is done with chmod 0755 code.sh.

  • If you need the shell script to work from a certain directory (i.e. the directory where the script is located) then build that into the script so it can be invoked with just ~/Desktop/code.sh:

    #!/bin/bash
    dir=$(dirname $0)
    cd $dir
    # do work
    

例如:

➜  ~  cat tmp/code.sh
#!/bin/bash
dir=$(dirname $0)
cd $dir
ls -l

➜  ~  chmod 0755 tmp/code.sh
➜  ~  tmp/code.sh
total 64
drwxr-xr-x   6 andy  staff    204 Feb 22 18:53 Archives
drwxr-xr-x  11 andy  staff    374 Jun 18 13:59 DerivedData
-rw-r--r--   1 andy  staff    225 May 20 13:44 MyFirstProgram.X
-rwxr-xr-x   1 andy  staff   3072 May 20 13:44 MyFirstProgram.exe
drwxr-xr-x   3 andy  staff    102 Jan  6  2014 bug_reports
-rwxr-xr-x   1 andy  staff     43 Aug  6 14:15 code.sh
-rw-r--r--   1 andy  staff  11539 May 20 08:33 iOS_Team_Provisioning_Profile_.mobileprovision
-rw-r--r--   1 andy  staff   1438 May 20 08:40 ios_development.cer
-rwxr-xr-x   1 andy  staff    272 Aug  5 08:55 script.sh

谢谢。这对于任何“正常”的Shell脚本都非常完美。 - Teletubbi-OS X
@Teletubbi-osx 抱歉,我不明白你在说什么。 - Droppy
1
你的例子运行得很完美! 我的问题是:我的shell脚本包含“材料”,可以轻松地通过iTerm / Terminal等运行,但无法从Automator中运行。我用5台OS X机器(macbook air,macbook pro,iMac; 10.9.4 / 10.9.5)重新创建了这个问题。 它总是一样的;从终端工作,不从自动化程序工作。所以显然autmator是问题所在。 当您执行 Rscript -e 'shiny :: runApp((“/ Users / Einstein / Git / RShiny / fooapp”),launch.browser = TRUE)' 通过终端,您可以看到加载过程并打开浏览器-完美。在Automator中,没有输出... - Teletubbi-OS X

3

解决方案

创建两个输出文件: 在 Automator 中: env > ~/Desktop/file_1.txt 在 iTerm 中: env > ~/Desktop/file_2.txt

区别

diff -y ~/Desktop/file_1.txt ~/Desktop/file_2.txt

然后,喜闻乐见的不同点出现了! 将差异插入脚本中,例如 export LANG=de_DE.UTF-8,它就可以工作了!


3
Automator和终端中的PATH变量不同是导致此问题的主要原因。Automator默认为PATH=/usr/bin:/bin:/usr/sbin:/sbin,而环境变量类似于PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin,因此Automator缺少/usr/local/bin。在Automator脚本中导出PATH确实可以解决此问题。 - Ninetou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接