2
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.

exitコマンドの終了コードを0にしたいときは、明示的に0を指定する

Posted at

exitコマンドの終了コード - @jkr_2255」という記事が面白かったので、自分の環境で実際に挙動を確認してみました。

環境

$ bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

出力結果

まず、exit コマンドは引数として指定した数字を終了コードとして返します。

$ bash -c 'exit 0'; echo $?
0
$ bash -c 'exit 1'; echo $?
1
$ bash -c 'exit 255'; echo $?
255

引数を指定せず、exitした場合は、終了コードが0となります。

$ bash -c 'exit'; echo $?
0

言及元の記事の通り、引数指定なしの exitコマンドの終了コードは、前回のコマンドの終了コードとなりました。

$ bash -c 'bash -c "exit 10"; exit'; echo $?
10

途中で psコマンドを発行してプロセスを確認してみます。exit 10を発行するプロセスが、exit を発行するプロセスの子プロセスになっていることがわかります。

$ bash -c 'bash -c "ps f;exit 10"; exit'; echo $?
10
22911 pts/0    Ss     0:00 bash
28813 pts/0    S+     0:00  \_ bash -c bash -c "ps f;exit 10"; exit
28814 pts/0    S+     0:00      \_ bash -c ps f;exit 10
28815 pts/0    R+     0:00          \_ ps f

余談

255以上の数値を指定すると、0を返すようです。

$ bash -c 'exit 256'; echo $?
0

コマンドのタイポをした場合は、127が返ります。

$ bash -c 'eecho;'; echo $?
bash: eecho: command not found
127

おわりに

特殊なケースでない限り、exit 0 と終了コードを明示的に指定しようと思います。トラブルが少なくて済みそうです。

2
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
2
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?