sh、bash、./xx.sh

来源:本站原创 点击数: 发布时间:2026年05月08日

一、一句话总结

  • sh xx.sh → 用 sh 解释器 运行脚本(兼容性强,功能少)
  • bash xx.sh → 用 bash 解释器 运行脚本(功能强,最常用)
  • ./xx.sh → 直接执行脚本(必须有执行权限,用脚本内指定的解释器)

二、详细区别(一看就懂)

1. sh xx.sh

  • 用系统默认的 sh(通常是 bash 的兼容模式 / dash)运行
  • 优点:兼容性最好,老脚本、嵌入式系统都能用
  • 缺点:不支持高级语法(比如 [[ ]]、数组等)
  • 不需要脚本有执行权限
sh install.sh

2. bash xx.sh

  • 用 bash 运行(Linux 标准 shell)
  • 优点:支持所有高级语法,我们写的脚本几乎都用它
  • 最推荐!
  • 不需要执行权限
  • 不需要执行权限
    bash install.sh

    3. ./xx.sh

    • 直接执行文件
    • 必须满足两个条件:
      1. 文件有 执行权限chmod +x xx.sh
      2. 脚本第一行写了 #!/bin/bash(指定解释器)
    • 最规范、最像“运行程序”的方式
    chmod +x install.sh
    ./install.sh

    三、你最关心的:我该用哪个?

    ✅ 日常 99% 推荐用这个

    bash xx.sh

    最稳定、功能最全、不用改权限、不用加头。

    ✅ 想最规范、像软件一样运行

    chmod +x xx.sh
    ./xx.sh

    ✅ 老脚本、不确定环境

    sh xx.sh

    四、超级精简记忆表

    命令
    解释器
    需要执行权限
    推荐场景
    sh xx.sh
    sh
    不需要
    兼容老系统
    bash xx.sh
    bash
    不需要
    日常使用
    ./xx.sh
    脚本内指定
    需要
    规范运行