maven-antrun-plugin可通过任务调用shell脚本,需指定executable="sh"(linux/macos)或cmd(windows),绑定到合适生命周期阶段,并设failonerror="true"确保失败中断;推荐优先使用exec-maven-plugin替代。

在 Maven 中通过 maven-antrun-plugin 执行 Shell 脚本是可行的,但需注意:AntRun 本身基于 Apache Ant,不直接支持 Shell 脚本(如 .sh),而是通过 <exec></exec> 任务调用系统命令。实际执行依赖操作系统和环境配置,且跨平台兼容性较弱。推荐优先考虑 maven-exec-plugin 或 exec-maven-plugin,但若必须使用 antrun,以下是可靠做法。
确认 antrun 插件版本并绑定到生命周期阶段
使用较新版本(如 3.0.0+)以获得更好兼容性和 Java 8+/11+ 支持。将插件配置在 <build><plugins></plugins></build> 中,并明确指定执行阶段(如 generate-resources、compile 或 package):
- 避免绑定到
clean或install等可能被跳过的阶段,除非有明确需要 - 确保
<phase></phase>与构建流程逻辑匹配,例如预编译处理脚本应放在process-classes前 - Windows 用户注意:
sh命令不可用,需改用cmd /c或 PowerShell
在 antrun 中调用 Shell 脚本(Linux/macOS)
通过 <exec executable="sh"></exec> 指定解释器,并传入脚本路径(建议使用 ${project.basedir} 定位):
<plugin><groupid>org.apache.maven.plugins</groupid><artifactid>maven-antrun-plugin</artifactid><version>3.1.0</version><executions><execution><id>run-shell-script</id><phase>generate-resources</phase><goals><goal>run</goal></goals><configuration><target><exec executable="sh" failonerror="true"><arg value="${project.basedir}/scripts/deploy.sh"></arg><arg value="--env"></arg><arg value="dev"></arg></exec></target></configuration></execution></executions></plugin>
关键点:
-
failonerror="true"确保脚本失败时 Maven 构建中断 - 脚本路径必须可读,且
deploy.sh需有执行权限(chmod +x scripts/deploy.sh) - 参数用多个
<arg></arg>分开传递,避免 shell 解析错误
Windows 兼容写法(避免硬编码 sh)
若需兼顾 Windows,可用 Ant 的 <os family="unix"></os> 和 <os family="windows"></os> 条件分支:
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
<target><condition property="script.exec" value="sh" else="cmd"><os family="unix"></os></condition><condition property="script.arg" value="/c" else=""><os family="windows"></os></condition><exec executable="${script.exec}" failonerror="true"><arg value="${script.arg}"></arg><arg value="${project.basedir}/scripts/build.bat"></arg></exec></target>
说明:
- Unix 系统执行
sh build.sh,Windows 执行cmd /c build.bat - 脚本内容应按平台分别编写,不要混用 bash 特性(如
[[ ]])在 bat 中 - 路径分隔符统一用正斜杠
/,Ant 会自动适配
替代方案更推荐 exec-maven-plugin
antrun 功能有限、配置冗长,且对复杂脚本支持差。生产项目中更常用 exec-maven-plugin:
<plugin><groupid>org.codehaus.mojo</groupid><artifactid>exec-maven-plugin</artifactid><version>3.1.0</version><executions><execution><id>run-shell</id><phase>prepare-package</phase><goals><goal>exec</goal></goals><configuration><executable>bash</executable><arguments><argument>${project.basedir}/scripts/validate.sh</argument><argument>${project.version}</argument></arguments></configuration></execution></executions></plugin>
优势:
- 原生支持
<executable></executable>和<arguments></arguments>,语义清晰 - 自动处理工作目录、环境变量(
<environmentvariables></environmentvariables>可设) - 支持异步执行、超时控制、输出重定向等高级选项
不复杂但容易忽略:Shell 脚本中的相对路径(如 ../config/app.yml)在 Maven 构建中是以 project.basedir 为起点解析的,务必在脚本内用 cd "$(dirname "$0")/.." 或 $(dirname $(readlink -f $0))/.. 显式切换上下文,否则易因执行路径不同而失败。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










