Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux exit 指令:登出 Shell 與結束腳本的正確姿勢

編輯:Linux 系統常見問題解答

指令用途

exit 用於結束目前的 Shell 階段(登出終端機)、或在 Shell 腳本中終止執行並回傳結束代碼。

語法

exit [n]
  • n:整數結束代碼(0~255),預設為前一個指令的結束代碼。0 代表成功,非 0 代表失敗。

常見使用情境

1. 互動式 Shell 登出

[root@rhel ~]# exit
logout
Connection closed.

2. Shell 腳本控制流程

#!/bin/bash
if [ ! -f /etc/myconfig ]; then
    echo "設定檔不存在"
    exit 1   # 非 0 結束代碼表示錯誤
fi
echo "設定檔存在,繼續執行"
exit 0

3. 巢狀 Shell 退回上層

bash          # 進入子 Shell
exit          # 回到父 Shell

4. SSH 連線中斷

在 SSH 會話中輸入 exit 或按 Ctrl+D 即可斷開連線。

結束代碼慣例

代碼含義
0成功
1一般錯誤
2用法錯誤(參數錯誤)
126指令不可執行(權限問題)
127指令不存在
128+n被信號 n 終止(如 130 = SIGINT/Ctrl+C)

小結

exit 是 Shell 控制流程的基本指令,善用結束代碼讓腳本可被其他程式判斷成敗,是撰寫健壯自動化腳本的關鍵。

Copyright © Windows教程網 All Rights Reserved