exit命令詳解

  

基礎命令學習目錄首頁html

 

原文連接:https://www.cnblogs.com/itcomputer/p/4157859.htmlshell

用途說明bash

exit命令用於退出當前shell,在shell腳本中能夠終止當前腳本執行。post

 

經常使用參數

格式:exit n學習

退出。設置退出碼爲n。(Cause the shell to exit with a status of n.)url

 

格式:exitspa

退出。退出碼不變,即爲最後一個命令的退出碼。(If n is omitted, the exit status is that of the  last  command executed. )code

 

格式:$?orm

上一個命令的退出碼。htm

 

格式:trap "commands" EXIT

退出時執行commands指定的命令。( A trap on EXIT is executed before the shell terminates.)

 

退出碼(exit status,或exit code)的約定:

0表示成功(Zero - Success)

非0表示失敗(Non-Zero  - Failure)

2表示用法不當(Incorrect Usage)

127表示命令沒有找到(Command Not Found)

126表示不是可執行的(Not an executable)

>=128 信號產生

 

man 3 exit 寫道
The C standard specifies two constants, EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate        successful or unsuccessful termination, respectively.

如下摘自/usr/include/stdlib.h

1
2
#define EXIT_FAILURE    1       /* Failing exit status.  */
#define EXIT_SUCCESS    0       /* Successful exit status.  */

 

BSD試圖對退出碼標準化。

man 3 exit 寫道
BSD has attempted to standardize exit codes; see the file <sysexits.h>.

 

如下摘自/usr/include/sysexits.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define EX_OK           0       /* successful termination */
#define EX__BASE        64      /* base value for error messages */
 
#define EX_USAGE        64      /* command line usage error */
#define EX_DATAERR      65      /* data format error */
#define EX_NOINPUT      66      /* cannot open input */
#define EX_NOUSER       67      /* addressee unknown */
#define EX_NOHOST       68      /* host name unknown */
#define EX_UNAVAILABLE  69      /* service unavailable */
#define EX_SOFTWARE     70      /* internal software error */
#define EX_OSERR        71      /* system error (e.g., can't fork) */
#define EX_OSFILE       72      /* critical OS file missing */
#define EX_CANTCREAT    73      /* can't create (user) output file */
#define EX_IOERR        74      /* input/output error */
#define EX_TEMPFAIL     75      /* temp failure; user is invited to retry */
#define EX_PROTOCOL     76      /* remote error in protocol */
#define EX_NOPERM       77      /* permission denied */
#define EX_CONFIG       78      /* configuration error */
 
#define EX__MAX 78      /* maximum listed value */

  

使用示例

示例一 退出當前shell

[root@new55 ~]# [root@new55 ~]# exit logout

 

示例二 在腳本中,進入腳本所在目錄,不然退出

Bash代碼
1
cd $( dirname $0) || exit 1

 

示例三 在腳本中,判斷參數數量,不匹配就打印使用方式,退出

1
2
3
4
if [ "$#" - ne "2" ]; then
     echo "usage: $0 <area> <hours>"
     exit 2
fi

示例四 在腳本中,退出時刪除臨時文件

1
trap "rm -f tmpfile; echo Bye." EXIT

示例五 檢查上一命令的退出碼

1
2
3
4
5
. /mycommand .sh
EXCODE=$?
if [ "$EXCODE" == "0" ]; then
     echo "O.K"
fi

功能說明:退出目前的shell。

 

語  法:exit [狀態值]

 

補充說明:執行exit可以使shell以指定的狀態值退出。若不設置狀態值參數,則shell以預設值退出。狀態值0表明執行成功,其餘值表明執行失敗。exit也可用在script,離開正在執行的script,回到shell。

相關文章
相關標籤/搜索