batファイルでコメントアウトしたい場合の方法を記入します。
スクリプトを作成する上でコメントアウトは大事ですよね。後から見たら何をしているのかわからなくなったりします。

複数人で開発する場合など共有の為にもコメントをきちんと書く事は大事です。
しかしスクリプトによってコメントアウトのやり方が違うので毎回忘れてしまう事もあります。
そこで今回はwindowsで一番簡単に使用できるbatファイルでのコメントアウトのやり方を共有します。
また複数行コメントアウトしたい場合などの方法も書いておきます。
batファイルを作成する時は未来の自分の為に、コメントアウトで説明文をきちんと書いておきましょう。
batファイルでコメントアウトする方法


batファイルでコメントアウトする方法を書いておきます。
- remでコメントアウトする
- :でコメントアウトする
- ::でコメントアウトする
「rem」でコメントアウトする方法
バッチファイルで良く使用するのがremコマンドです。REMと大文字で書いても問題ありません。
rem コメント
REM コメント
基本的にはこのコマンドでコメントする事がほとんどです。
特に問題なければremコマンドを使用しましょう!


「:」でコメントアウトする方法
「:」コロンを使用してもコメントアウト出来ます。
: コメント
コロンでも出来ます。しかし「goto」コマンドでラベルが付いた箇所の行に移動するコマンドがありますが、その宛先でも「:」が使用される為、混乱を招く恐れがあります。


その解決策としてあるのが「::」を使用する方法です。
「::」でコメントアウトする方法
「::」コロン2つでもコメントアウトになります。
:: コメント
こちらもあまり使用しませんが、「:」を使用するぐらいなら「::」を使用しましょう!
batファイルで複数行コメントアウトする方法


複数行コメントアウトしたい場合もあると思います。
他の言語であれば複数行コメントアウトする方法がありますがbatにはありません。
なのですべての行に「rem」を使用しましょう。
rem 複数行
rem コメントアウト
rem したい
batファイルでコメントアウトを確認してみよう


では本当にコメントアウトできるか確認しましょう!
batファイルを作成して以下のコマンドを書きましょう!
rem echo コメント1 >> bat_commentout.txt
echo コメントの書き方1は「rem」>> bat_commentout.txt
: echo コメント2 >> bat_commentout.txt
echo コメントの書き方2は「:」>> bat_commentout.txt
:: echo コメント3 >> bat_commentout.txt
echo コメントの書き方3は「::」>> bat_commentout.txt
コメントするコマンドの説明
すべての行に「echo」コマンドを使用して表示させるようにします。


batファイルをダブルクリックでも確認できるようにリダイレクト「>>」でファイルに書き出ししています。
batファイルを実行したらbatと同じフォルダに「bat_commentout.txt」ファイルが作成されて追記されるはずです。


batファイルでコメントアウト出来ているか確認
batファイルをダブルクリックして実行してみましょう。


同じフォルダに「bat_commentout.txt」ファイルが作成されており、中身を見ると以下になっています。
コメントの書き方1は「rem」
コメントの書き方2は「:」
コメントの書き方3は「::」
コメントアウトしたい行は表示されていない事が確認出来ます。
成功しています。


batファイルでコメントが文字化けしている時の対処法


文字列が文字化けしたり、何も起きない可能性もあります。
文字コードが間違っている可能性があります。
文字コードを変更するには以下の手順で行いましょう!
- batファイルを開く
- 名前を付けて保存をする
- 文字コードを「SJIS」か「ANSI」にして上書き保存する


まとめ:batファイルでコメントアウトする方法


まとめておきます。
- remでコメントアウトする
- :でコメントアウトする
- ::でコメントアウトする
「rem」を使用しましょう!「REM」でも良いです。
「:」を使用するぐらいなら「::」を使用しましょう!