MacOS 更喜欢 /bin/sh 还是 /bin/bash?

ter*_*boy 4 macos bash shell terminal

我想与某人共享一个脚本,但不确定 MacOS 上首选哪个。哪一个最好支持?

这?

#!/bin/sh
echo "Here goes my simple script that changes some settings."
# ... do some stuff
Run Code Online (Sandbox Code Playgroud)

或这个?

#!/bin/bash
echo "Here goes my simple script that changes some settings."
# ... do some stuff
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 11

您应该选择与编写脚本所用的 shell 方言/语言相对应的 shebang。

  • 如果您为 POSIX sh 编写,请使用#!/bin/sh

  • 如果您为 Zsh 编写,请使用#!/usr/bin/env zsh

  • 如果您为 Fish 写作,请使用#!/usr/bin/env fish

  • 如果你为 Bash 编写,请使用#!/usr/bin/env bash* (如果你不知道,这可能就是它)

sh大致bash相当于 C 与 C++ 的关系,您应该知道要使用哪一个。有关更多信息,请参阅sh 和 bash 之间的区别为什么我的 bash 代码在使用 sh 运行时会失败?


* 使用env这种方式相当于#!/bin/bash,但也允许用户安装更新版本的 Bash。macOS 上的用户尤其会这样做,因为该操作系统附带了过时的版本。