如何在Maven中source Shell脚本?两种插件尝试均失败
问题
我需要让Maven通过source run.sh加载Shell脚本,而非直接执行./run.sh。试了两种插件配置都失败了:
尝试的配置1:exec-maven-plugin
<plugin> <artifactId>exec-maven-plugin</artifactId> <groupId>org.codehaus.mojo</groupId> <executions> <execution> <id>source file</id> <phase>process-resources</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>source</executable> <arguments> <argument>./run.sh</argument> </arguments> </configuration> </execution> </executions> </plugin>
尝试的配置2:maven-antrun-plugin
<plugin> <artifactId>maven-antrun-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId> <executions> <execution> <id>source file</id> <phase>process-resources</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <exec executable="source"> <arg value="./run.sh"/> </exec> </target> </configuration> </execution> </executions> </plugin>
两种配置都报错,提示source命令不存在。
根因
source是Shell内置命令,不是独立可执行文件,没法直接作为executable参数指定。必须通过调用Shell解释器(比如bash)来间接执行source操作。
正确配置
方案1:exec-maven-plugin
用bash的-c参数执行source命令:
<plugin> <artifactId>exec-maven-plugin</artifactId> <groupId>org.codehaus.mojo</groupId> <executions> <execution> <id>source-runsh</id> <phase>process-resources</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>bash</executable> <arguments> <argument>-c</argument> <argument>source ./run.sh</argument> </arguments> <!-- 若需后续Maven步骤继承脚本环境变量,必须开启此项 --> <shell>true</shell> </configuration> </execution> </executions> </plugin>
提示:如果脚本里的环境变量要被后续Maven阶段读取,一定要加
<shell>true</shell>,让命令在同一个Shell进程中执行。
方案2:maven-antrun-plugin
同样通过bash执行source:
<plugin> <artifactId>maven-antrun-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId> <executions> <execution> <id>source-runsh</id> <phase>process-resources</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <exec executable="bash"> <arg value="-c"/> <arg value="source ./run.sh"/> </exec> </target> </configuration> </execution> </executions> </plugin>
额外提示
- 若系统默认Shell不是bash,把
bash换成对应解释器即可(比如zsh)。 - 为避免相对路径问题,可用Maven内置变量
${project.basedir}指定脚本绝对路径:<argument>source ${project.basedir}/run.sh</argument>
内容的提问来源于stack exchange,提问作者Kyle Seaman
相关产品推荐
相关产品推荐

