Windows
bat
コマンドプロンプト
batch
バッチファイル

batファイルでコマンドの実行結果を出力しないようにする方法

More than 1 year has passed since last update.

ターゲット

  • 普段batファイルを使用していて、コマンドの実行結果をコマンドプロンプトに出力したくない
  • @echo off をすでに使用している

結論

コマンドの末尾に > nul を付ける

実行結果

C:\Windows\system32>echo hoge
hoge

C:\Windows\system32>echo hoge > nul

理由

> はリダイレクトといい、出力先をコマンドプロンプトでなく指定したファイルに変更します。
nul は空(のファイル)という意味で、書き込んでも何も起きません。
つまり、> nul で出力先を空のファイルに変更することで、コマンドプロンプト上には何も出力されなくなります。

おまけ

> nul を付けただけだと、エラーメッセージは出力されてしまいます。
さらに 2>&1 を付けることで、エラーメッセージも出力されなくなります。

実行結果

C:\Windows\System32>mkdir hoge > nul

C:\Windows\System32>mkdir hoge > nul
サブディレクトリまたはファイル hoge は既に存在します。

C:\Windows\System32>rmdir hoge

C:\Windows\System32>mkdir hoge > nul 2>&1

C:\Windows\System32>mkdir hoge > nul 2>&1

C:\Windows\System32>cd hoge

理由

2> はエラーメッセージをリダイレクトするという意味で、&1 は通常の出力という意味です。
つまり、 2>&1 でエラーメッセージを通常の出力にリダイレクトし、 > nul で通常の出力を空のファイルにリダイレクトすることで、エラーメッセージも空のファイルにリダイレクトされます。
イメージとしては「標準エラー出力→標準出力→空のファイル」です。
ちなみに通常の出力を「標準出力」、エラーメッセージを「標準エラー出力」といいます。

参考リンク

Why do not you register as a user and use Qiita more conveniently?
You seem to be reading articles frequently this month. You can use this function by logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away