Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux管理 >> Linux維護

用 whiptail 寫出終端機互動選單:Email 管理腳本實例

純指令環境也能有漂亮的互動介面。whiptail 提供選單、輸入框、確認框、進度條等元件,讓 shell 腳本搖身一變成為操作友善的小工具。

完整範例

#!/bin/bash
trap "" 2
while true
do
OPTION=$(whiptail --title "Email Manager" --nocancel --menu "Choose your option" 15 60 4 \
  "1" "Add Email User" \
  "2" "Delete Email User" \
  "3" "List Email User" \
  "4" "EXIT" 3>&1 1>&2 2>&3)

case $OPTION in
  1) EmailAddress=$(whiptail --title "Input Box" --inputbox "What is your add EmailAddress?" 10 60 @shenxu.com 3>&1 1>&2 2>&3)
     ... ;;
  2) EmailAddress=$(whiptail --title "Input Box" --inputbox "Delete EmailAddress?" 10 60 3>&1 1>&2 2>&3)
     ... ;;
  3) whiptail --msgbox "The list is ..." --scrolltext 20 40 ;;
  4) break ;;
esac
done

參數怎麼讀

  • --title "Email Manager":視窗標題。
  • --nocancel:只顯示 OK,隱藏取消鈕。
  • --menu "提示文字" 15 60 4:高度 15、寬度 60、可見選項 4 個。
  • --inputbox "提示" 10 60 預設值:讓使用者輸入文字。
  • --msgbox "訊息" 10 40:顯示單段提示。
  • --scrolltext 20 40:內容過長時可上下捲動。
  • --passwordbox:輸入內容以星號遮蔽。
  • --checklist "choose" 15 60 2 "1" "aa" ON "2" "bb" OFF:多選清單,ON/OFF 決定預設是否勾選,用空白鍵切換。
  • --radiolist:單選版,只能有一項 ON。
  • --gauge:進度條。
{ for n in `seq 100`; do sleep 1; echo $n; done; } | whiptail --gauge "Please wait" 6 60 0

最關鍵的一行是 3>&1 1>&2 2>&3。whiptail 把結果寫在 fd 3,這段描述符重排技巧把它導回 stdout 存進變數,同時保留 stderr 給介面繪製使用。少了它,選單畫面就會被存進變數裡。

Copyright © Linux教程網 All Rights Reserved