4

mvn clean在终端上可以正常工作。即使我通过双击从 bash 文件(.sh 文件)执行相同的操作,它也可以正常工作。

但是当我使用 crontab 触发相同的操作时,我得到了一个错误mvn:command not found

bash(.sh) 文件有这个代码

#!/bin/bash 
cd /Users/testautomation/Documents/Automation/TFS/Mem_Mobile 
mvn clean

crontab -l 的输出

0 14 * * * /Users/testautomation/Documents/Automation/Schedule/Execute.sh

错误

From testautomation@Tests-iMac.xxx.local  Wed Jun 12 14:44:01 2019
Return-Path: <testautomation@Tests-iMac.xxx.local>
X-Original-To: testautomation
Delivered-To: testautomation@Tests-iMac.xxx.local
Received: by Tests-iMac.xxx.local (Postfix, from userid 501)
id 0BE233001CB411; Wed, 12 Jun 2019 14:44:00 +1000 (AEST)
From: testautomation@Tests-iMac.xxx.local (Cron Daemon)
To: testautomation@Tests-iMac.xxx.local
Subject: Cron <testautomation@Tests-iMac> /Users/testautomation/Documents/Automation/Schedule/Execute.sh
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=testautomation>
X-Cron-Env: <USER=testautomation>
X-Cron-Env: <HOME=/Users/testautomation>
Message-Id: <20190612044401.0BE233001CB411@Tests-iMac.xxx.local>
Date: Wed, 12 Jun 2019 14:44:00 +1000 (AEST)

/Users/testautomation/Documents/Automation/Schedule/Execute.sh: line 3: mvn: command not found

我已经使用自制软件安装了 Maven。

mvn -version输出 :

Tests-iMac:~ testautomation$ mvn -version
Apache Maven 3.6.1 (d66c9c0b3152b2e69ee9bac180bb8fcc8e6af555; 2019-04-05T06:00:29+11:00)
Maven home: /usr/local/Cellar/maven/3.6.1/libexec
Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre
Default locale: en_AU, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "Mac"
4

4 回答 4

1

就像在这里一样,您可能需要添加环境变量 (MAVEN_HOME) 并完成 PATH(其中一个 for mvn

或者至少在您的 script.sh 中做同样的事情,这意味着不要假设您会在 cron 会话中继承所有用户会话环境。

于 2019-06-12T05:38:48.250 回答
1

Cron 运行非非活动和非登录 shell

0 14 * * * . $HOME/.profile; /Users/testautomation/Documents/Automation/Schedule/Execute.sh

如果您使用更多 shell 配置文件变量扩展您的 shell 脚本,上述命令非常适合。加载 bash 配置文件会更新 env 变量,包括 PATH 变量以包含 mvns 路径(主要是在安装 mvn 期间添加到其中的)

.是 的同义词source

crontab 在非常有限的 shell 环境中运行。设置了一些变量,例如 HOME、LOGNAME 和 SHELL。这就是我们可以使用 $HOME 调用相应配置文件的原因。

PATH 应该包含您的 mvn 二进制文件的位置,但仅限于 cron env 中的主要二进制路径;因此,您的 mvn 二进制文件的绝对路径如前所述。

于 2019-06-12T08:46:23.553 回答
1

执行脚本时使用mvn的完整路径。

#!/bin/bash 
cd /Users/testautomation/Documents/Automation/TFS/Mem_Mobile 
/usr/local/Cellar/maven/3.6.1/bin/mvn clean

或者下面的脚本也应该工作

#!/bin/bash 
cd /Users/testautomation/Documents/Automation/TFS/Mem_Mobile 
/usr/local/bin/mvn clean
于 2019-06-12T06:19:56.357 回答
0

一个不错的方法是将 mvn 的路径声明为字符串值,并使用“$val”调用它:

mvn="path\to\mvn" -- 等号附近没有空格

然后调用“$mvn”

于 2021-06-03T15:25:22.693 回答