bashのシェルを動かしたら line 1: #!/bin/bash: No such file or directory となった場合の対応方法


事象:シェルは実行されるけれどなんかいわれている

# シェルの中身
$ cat ~/Desktop/shell_kind.sh 
#!/bin/bash

canuse=`cat /etc/shells`
echo '使用可能なシェルの種類:'"$canuse"
echo '使っているシェルの種類:'$SHELL
echo '今動かしているシェルの名前:'$0

# 動かしてみるとなんかいわれている
$ bash shell_kind.sh 
shell_kind.sh: line 1: #!/bin/bash: No such file or directory # <<<<< なんかいわれている
使用可能なシェルの種類:# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
使っているシェルの種類:/bin/bash
今動かしているシェルの名前:shell_kind.sh

原因:ファイルの文字コードが UTF-8 with BOM だから

文字コードをみてみる
$ file shell_kind.sh 
shell_kind.sh: Bourne-Again shell script text executable, UTF-8 Unicode (with BOM) text

対応:ファイルの文字コードをUTF-8 にする

# BOMを削除してUTF-8にする。
$ nkf --overwrite --oc=utf-8 shell_kind.sh 
$ file shell_kind.sh 
shell_kind.sh: Bourne-Again shell script text executable, UTF-8 Unicode text

コマンドでのBOMの削除・確認 - Qiita