stty (Set TTY) 用於讀取/修改終端機列印列特性,包含輸入/輸出處理、控制字元、傳輸速率等。本文系統整理常用參數與實戰應用場景。
stty -a # 顯示所有目前設定 (人類可讀)
stty -g # 顯示十六進位設定碼 (可用於還原)
old=$(stty -g) # 變數儲存目前設定
stty "$old" # 還原設定
| 功能 | 啟用 | 停用 | 說明 |
|---|---|---|---|
| 標準輸入模式 (行緩衝) | stty icanon | stty -icanon | 預設啟用,Enter 才送出 |
| 原始模式 (字元級) | stty raw | stty -raw | 關閉所有輸入處理,含 -icanon -echo 等 |
| 回顯輸入字元 | stty echo | stty -echo | 密碼輸入時常用 -echo |
| 大寫轉小寫輸入 | stty iuclc | stty -iuclc | 輸入大寫自動轉小寫 |
| 忽略 CR (^M) | stty igncr | stty -igncr | 處理 DOS 換行檔 |
| 功能 | 啟用 | 停用 | 說明 |
|---|---|---|---|
| 小寫轉大寫輸出 | stty olcuc | stty -olcuc | 終端機輸出全大寫 |
| NL->CR-NL 轉換 | stty onlcr | stty -onlcr | 預設啟用,換行自動加回車 |
stty eof "^D" # EOF 字元 (預設 Ctrl+D)
stty eof "x" # 改為 x 字元
stty erase "^H" # 刪除字元 (Backspace)
stty kill "^U" # 刪除整行
stty intr "^C" # 中斷訊號 (SIGINT)
stty susp "^Z" # 暫停訊號 (SIGTSTP)
stty size # 輸出: 行 列 (例: 24 80)
stty rows # 僅顯示行數
stty cols # 僅顯示列數
stty 9600 # 設定輸入/輸出速率
stty ispeed 9600 # 僅輸入速率
stty ospeed 115200 # 僅輸出速率
read_password() {
local old=$(stty -g)
stty -echo
read -r password
stty "$old"
echo
}
get_key() {
local old=$(stty -g)
stty -icanon -echo min 0 time 10 # 1秒逾時
dd bs=1 count=1 2>/dev/null
stty "$old"
}
現代 Bash 直接用 read -t 1 -n 1 key 更簡潔。
stty -icanon -echo igncr
cat winfile.txt | while IFS= read -r line; do
process "$line"
done
stty sane # 重置為合理預設值
stty -F /dev/ttyUSB0 115200 cs8 -cstopb -parenb -echo -ixon -ixoff
# 115200 8N1, 關閉回顯/流控
stty sane
# 等效於:
# icanon echo echoe echok -echoctl -echoke intr ^C erase ^? kill ^U ...
stty -a | grep -E 'speed|rows|cols|eof|erase|kill|intr|susp' 快速檢視關鍵值reset 或 stty sane 恢復exec bash 重置stty 是終端機行為微調的核心工具,理解其參數對開發終端機應用、序列通訊、自動化測試腳本至關重要。