萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 終端機控制利器:stty 指令參數完整速查與實戰應用

stty (Set TTY) 用於讀取/修改終端機列印列特性,包含輸入/輸出處理、控制字元、傳輸速率等。本文系統整理常用參數與實戰應用場景。

基本查詢與備份

stty -a              # 顯示所有目前設定 (人類可讀)
stty -g              # 顯示十六進位設定碼 (可用於還原)
old=$(stty -g)       # 變數儲存目前設定
stty "$old"          # 還原設定

輸入模式控制

功能啟用停用說明
標準輸入模式 (行緩衝)stty icanonstty -icanon預設啟用,Enter 才送出
原始模式 (字元級)stty rawstty -raw關閉所有輸入處理,含 -icanon -echo 等
回顯輸入字元stty echostty -echo密碼輸入時常用 -echo
大寫轉小寫輸入stty iuclcstty -iuclc輸入大寫自動轉小寫
忽略 CR (^M)stty igncrstty -igncr處理 DOS 換行檔

輸出模式控制

功能啟用停用說明
小寫轉大寫輸出stty olcucstty -olcuc終端機輸出全大寫
NL->CR-NL 轉換stty onlcrstty -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   # 僅輸出速率

實戰應用範例

1. 密碼輸入不回顯 (Shell 腳本)

read_password() {
    local old=$(stty -g)
    stty -echo
    read -r password
    stty "$old"
    echo
}

2. 非阻塞單字元讀取 (選單互動)

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 更簡潔。

3. 處理 Windows (CRLF) 文字檔

stty -icanon -echo igncr
cat winfile.txt | while IFS= read -r line; do
    process "$line"
done
stty sane  # 重置為合理預設值

4. 序列埠連線設定

stty -F /dev/ttyUSB0 115200 cs8 -cstopb -parenb -echo -ixon -ixoff
# 115200 8N1, 關閉回顯/流控

stty 參數示意

重置為合理預設

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 恢復
  • SSH 連線異常斷開導致終端機狀態錯亂,重新登入或 exec bash 重置

stty 是終端機行為微調的核心工具,理解其參數對開發終端機應用、序列通訊、自動化測試腳本至關重要。

copyright © 萬盛學電腦網 all rights reserved