3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

シェルスクリプト (bash等) で if - then - else の中身をコメントアウトした時のエラーの回避方法

Last updated at Posted at 2022-01-13

TL;DR

シェルスクリプト(POSIX 準拠)では if - then - else の中をコメントだけ、または空にしてはいけません。以下のシェルスクリプトを POSIX シェル(dash, bash, ksh 等)や Bourne シェルで実行するとエラーになります。

if true; then
  # echo "この行をコメントアウト"
fi

# 何も書かない場合も同様
if true; then
fi

このエラーは : (何もしないコマンド)を入れると回避できます。

if true; then
  : # echo "この行をコメントアウト"
fi

if true; then
  : echo "この行をコメントアウト" # このような書き方でも良い
fi

何かしらの実行可能なコードを入れれば良いので : だけではなく任意のコマンドや変数代入や関数定義などでも構いません。

解説

POSIX シェルの文法では if 文の if - then - elif - else - fi、for 文や while 文の for, while - do - done{ } といった複合コマンドの中身を空にすることはできません。そのため bash 含む POSIX に準拠しているシェルや Bourne シェルではエラーになります。ただし例外的にエラーにならないシェル(zsh, yash, FreeBSD sh 等)もあります。

なお通常は中身を空にする必要はありません。開発中やデバッグなどで一時的に空だったりコメントアウトしたい時ぐらいでしょう。

# 例

if true; then
  # 何もしない
else
  echo "false"
fi

# ↓ このように書けば良い

if ! true; then
  echo "false"
fi

エラーメッセージ

ちなみにエラー(文法エラー)の内容はこのようなものです。本来コマンドが来るべき所で予期せぬ fi (予約語)が来ているためこのようなエラーとなります。

dash

$ dash script.sh
script.sh: 5: script.sh: Syntax error: "fi" unexpected

bash

$ bash script.sh
script.sh: 行 5: 予期しないトークン `fi' 周辺に構文エラーがあります
script.sh: 行 5: `fi'

$ LANG=C bash script.sh # 英語の場合
script.sh: line 5: syntax error near unexpected token `fi'
script.sh: line 5: `fi'

ksh93

$ ksh script.sh
script.sh: syntax error at line 5: `fi' unexpected

mksh

$ mksh script.sh
script.sh[5]: syntax error: unexpected 'fi'

ksh88 (Solaris 10)

$ /usr/bin/ksh script.sh
script.sh[3]: syntax error at line 6 : `fi' unexpected

Bourne shell (Solaris 10)

$ /bin/sh script.sh
script.sh: syntax error at line 6: `fi' unexpected

注意 Bourne shell 自身は POSIX に準拠していませんが、POSIX シェルに類するシェル(bash 等)の元となったシェルです。主に商用 UNIX で使われていたシェルですが、現在は ksh に取って代わられており Bourne shell が使われることはほぼありません。昔からのシェルの仕様であることを示すためにこの記事では参考として記載しています。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?