Whiptail 是一個用于創建簡單圖形界面的命令行工具,它可以在 Linux 系統中運行
安裝 Whiptail:
對于基于 Debian 的系統(如 Ubuntu),請使用以下命令安裝 Whiptail:
sudo apt-get update
sudo apt-get install whiptail
對于基于 RHEL 的系統(如 CentOS),請使用以下命令安裝 Whiptail:
sudo yum install newt
編寫一個簡單的 Whiptail 腳本:
創建一個名為 whiptail_example.sh
的文件,并添加以下內容:
#!/bin/bash
# 顯示一個簡單的消息框
whiptail --msgbox "Hello, this is a simple message box." 8 78
# 顯示一個帶有選項的菜單
choice=$(whiptail --title "Menu Example" --menu "Choose an option:" 10 60 3 \
"1" "Option 1" \
"2" "Option 2" \
"3" "Option 3" 3>&1 1>&2 2>&3)
# 根據所選選項執行操作
case $choice in
1)
echo "You chose Option 1."
;;
2)
echo "You chose Option 2."
;;
3)
echo "You chose Option 3."
;;
esac
保存文件并為其添加可執行權限:
chmod +x whiptail_example.sh
運行腳本:
在終端中運行腳本:
./whiptail_example.sh
使用變量和函數:
使用變量和函數可以使 Whiptail 腳本更具可讀性和可重用性。例如,您可以創建一個函數來顯示一個輸入框,并將用戶輸入的值存儲在一個變量中。
#!/bin/bash
function input_box() {
local title="$1"
local prompt="$2"
local default="$3"
local height=10
local width=60
local input=$(whiptail --title "$title" --inputbox "$prompt" $height $width "$default" 3>&1 1>&2 2>&3)
echo $input
}
name=$(input_box "Name Input" "Please enter your name:" "")
age=$(input_box "Age Input" "Please enter your age:" "25")
echo "Your name is $name and you are $age years old."
錯誤處理:
在使用 Whiptail 時,確保正確處理可能出現的錯誤。例如,當用戶取消操作或輸入無效數據時,Whiptail 會返回非零退出狀態。您可以使用 if
語句檢查這些情況,并相應地處理它們。
#!/bin/bash
name=$(whiptail --title "Name Input" --inputbox "Please enter your name:" 10 60 "" 3>&1 1>&2 2>&3)
if [ $? -ne 0 ]; then
echo "Operation cancelled by user."
exit 1
fi
echo "Your name is $name."
通過遵循這些最佳實踐,您可以創建功能豐富且易于維護的 Whiptail 腳本。