🐚

1分で分かる、今さら聞けない Shebang

2024/02/16に公開

Shebang とは

Shebang (シバン / シェバン / シバング) は, Unix系OSで使用される特殊なコメントです. スクリプトファイルが使用するインタプリタを指定するもので, ファイルの先頭に記述します.

特にシェルスクリプトの場合は, 利用者によっては使用しているシェルが異なる場合も少なくありません. どのシェルから利用しても同じインタプリタが使用されるようにShebangをしっかり記述しておくことが望ましいです.

Shebang で遊んでみよう

シェルスクリプトの例

下記スクリプトを ./hello.sh として保存します. ( chmod +x も忘れずに.)

./hello.sh
#!/bin/bash
 
ps -p $$

それを実行するとこのようになります.

% ps -p $$  # 現在のシェルを確認します(zshです)
  PID TTY           TIME CMD
10413 ttys000    0:00.52 -zsh
 
% ./hello.sh
  PID TTY           TIME CMD
 8115 ttys001    0:00.01 /bin/bash ./hello.sh
%

/bin/bash が使われていますね! 🎉

なお, sh に直接スクリプトを渡した場合は Shebang は評価されません.

% sh ./hello.sh
  PID TTY           TIME CMD
39563 ttys001    0:00.01 sh ./hello.sh

続いて bashsh に変更してみます.

./hello.sh
#!/bin/sh
 
ps -p $$
% ./hello.sh
  PID TTY           TIME CMD
 8314 ttys001    0:00.01 /bin/sh ./hello.sh
%

言わずもがなですが, /bin/sh で実行されました! 🎉

Pythonの例

下記の2ファイルを作成し, chmod +x で実行権限をつけます.

./hello_python_3.py
#!/usr/bin/python3
 
import sys
 
print(sys.version)
./hello_python_2.py
#!/usr/bin/python2
 
import sys
 
print(sys.version)

それぞれ実行すると次のようになります.

$ ./hello_python_2.py
2.7.17 (default, Jul 20 2020, 15:37:01)
[GCC 7.5.0]
 
$ ./hello_python_3.py
3.6.9 (default, Jul 17 2020, 12:50:27)
[GCC 8.4.0]

なお, Python のインタプリタは Shebang を評価しません.

% python -V
Python 3.11.5
% python ./hello_python_2.py
3.11.5 (main, Oct  2 2023, 14:07:24) [Clang 14.0.3 (clang-1403.0.22.14.1)]

昨今はPythonでスクリプトを書くシチュエーションは限りなく少なくなってきましたので, 参考程度にしてください. 🙇🏻‍♂️

FYI: /usr/bin/env を活用しよう!

/usr/bin/env を用いた Shebang の設定を個人的に推奨します.

#!/usr/bin/env bash#!/usr/bin/env python と記述すると, PATH などのユーザー設定も含めた上でインタプリタが決定されます.
(ただしPython等のバージョン指定まではできませんが)

パスで #!/bin/bash と指定するよりもポータビリティが高いと言えると思います.

MacOS で brew install bash をしている場合には, /opt/homebrew/bin/bash が自動で使われるので大変便利です. 😆

#!/usr/bin/env bash の使用例
% /bin/bash --version
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin22)
Copyright (C) 2007 Free Software Foundation, Inc.
 
% /opt/homebrew/bin/bash --version
GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin21.6.0)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
 
% cat ./hello.sh
#!/usr/bin/env bash
 
echo "BASH_VERSINFO: ${BASH_VERSINFO}"
 
ps -p $$

# brew で入れた bash が使われている! :tada:
% ./hello.sh
BASH_VERSINFO: 5
  PID TTY           TIME CMD
88098 ttys002    0:00.00 bash ./hello.sh
%

また, /usr/bin/envwhich のノリで叩けるので, 覚えておくとトラブルシューティングの際に役立つかもしれません.

% /usr/bin/env bash --version
GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin21.6.0)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Discussion