4
3

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 5 years have passed since last update.

バッチファイルを誤って起動しないようにするおまじない

Last updated at Posted at 2019-07-13

本番環境でバッチファイルをついうっかりダブルクリックやEnterで誤って起動してしまい真っ青になる経験は誰しもがあるのではないでしょうか?(あるよね?)

誤って起動しても事なきを得るためのおまじない(コード)がこちらです。

:: コマンドライン引数に1を渡していないと終了する
if "%1" neq "1" (
	exit /b
)

ダブルクリックではコマンドライン引数が渡されないので、
これを処理の頭に書いておくと次処理に行かず終了してくれます。

引数と比較する値は別に1じゃなくてもなんでもよいです。

ちゃんと実行したいときはこのように引数を渡して実行します。
>hoge.bat 1

他のバッチファイルやプログラムから実行するのではなく、人が実行するのならchoiceコマンドを使うのもアリです。

choice /c YN /M "実行しますか?"
if %ERRORLEVEL% equ 1 goto exec
exit /b

:exec
~処理~

choiceコマンドはyかnの入力をメッセージ付きで促せるコマンドです。
yを押すとERRORLEVEL変数に1が入るので上記のような記述が可能です。

>choice /c YN /M "実行しますか?"
実行しますか? [Y,N]?Y

>echo %ERRORLEVEL%
1

>choice /c YN /M "実行しますか?"
実行しますか? [Y,N]?N

>echo %ERRORLEVEL%
2

ご安全に!

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?