You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu下make命令在Shell脚本中执行报错,命令行直接执行正常

问题解决:Shell脚本执行make时提示chmod命令找不到,命令行直接运行正常

问题描述

在Ubuntu环境中,用户编写的Shell脚本如下:

#!/bin/bash

cd path/to/directory
/usr/bin/perl Makefile.PL
/usr/bin/make

执行该脚本时出现如下错误:

Checking if your kit is complete...
Looks good
Warning: prerequisite B::COW 0.004 not found.
Generating a Unix-style Makefile
Writing Makefile for Clone
Writing MYMETA.yml and MYMETA.json
make: chmod: Command not found
Makefile:397: recipe for target 'blib/lib/.exists' failed
make: *** [blib/lib/.exists] Error 127

但直接在命令行手动执行perl Makefile.PL和make命令时,却能正常运行无报错。

原因分析

报错的核心原因是非交互式Shell脚本的环境变量PATH与交互式Shell的PATH不一致。交互式Shell(手动打开的终端)会加载~/.bashrc、/etc/profile等配置文件,从而包含/bin、/usr/bin这类存放chmod命令的路径;而Shell脚本默认以非交互式模式运行,默认的PATH路径更精简,导致make无法找到chmod命令。

另外,报错中的B::COW 0.004 not found只是测试依赖缺失的警告,不会影响编译过程,不是当前报错的根源。

解决方法

以下几种方法均可解决问题:

  • 方法一:在脚本开头显式设置完整的PATH
    在脚本最开头添加export PATH语句,包含所有必要的系统命令路径:

    #!/bin/bash
    # 显式设置完整PATH,确保包含chmod所在的路径
    export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    
    cd path/to/directory
    /usr/bin/perl Makefile.PL
    /usr/bin/make
    
  • 方法二:让脚本加载交互式Shell的配置
    在脚本开头添加加载~/.bashrc的语句,复用交互式Shell的环境变量:

    #!/bin/bash
    # 加载当前用户的bash配置文件
    . ~/.bashrc
    
    cd path/to/directory
    /usr/bin/perl Makefile.PL
    /usr/bin/make
    

    注意:如果~/.bashrc中有仅针对交互式Shell的逻辑(比如判断[[ $- == *i* ]]),可能需要调整配置,避免不必要的干扰。

  • 方法三:修改Makefile使用chmod的绝对路径
    执行perl Makefile.PL生成Makefile后,编辑Makefile文件,将所有chmod替换为绝对路径(比如/bin/chmod),但这种方法需要每次生成Makefile后修改,不如前两种方法便捷。

内容的提问来源于stack exchange,提问作者Ira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:42:44