很多人誤以為shell腳本只能在命令行下使用。其實shell也可以調用一些GUI組件,例如菜單,警告框,進度條等等。你可以控制最終的輸出,光標位置還有各種輸出效果。下面我將介紹一些工具,幫助你創建強大的,互動的,用戶友好的 Unix/Linux shell腳本。我在FreeBSD和Linux下測試過這些工具,不過其他UNIX系列的操作系統應該都支持的。
1. notify-send 命令
這個命令可以讓你通過通知進程發送一個桌面通知給用戶。這可以用來向用戶發送提示,或者顯示一些信息而不用打斷用戶工作。你需要安裝如下軟件包:
1
$
sudo
apt-get
install
libnotify-bin
下面這個例子展示了如何從命令行向桌面發送一個簡單的消息:
1
notify-send
"rsnapshot done :)"
輸出:
下面是一個復雜一點的例子:
1
....
2
alert=18000
3
live=$(lynx --dump http://money.rediff.com/ |
grep
'BSE LIVE'
|
awk
'{ print $5}'
|
sed
's/,//g;s/\.[0-9]*//g'
)
4
[ $notify_counter -
eq
0 ] && [ $live -
ge
$alert ] && { notify-send -t 5000 -u low -i
"BSE Sensex touched 18k"
; notify_counter=1; }
5
...
輸出:
這裡的參數解釋如下:
- -t 5000:指定超時的時間,毫秒
- -u low:設置是否緊急
- -i gtk-dialog-info:通知圖標,你可以指定圖標 -i /path/to/your-icon.png
2. tput 命令
這個命令是用來設置終端特性的:
- 移動光標
- 獲得終端信息
- 設置前景和背景色
- 設置粗體模式
- 設置反模式等等
舉例:
01
02
03
04
tput
clear
05
06
07
tput cup 3 15
08
09
10
tput setaf 3
11
echo
"XYX Corp LTD."
12
tput sgr0
13
14
tput cup 5 17
15
16
tput rev
17
echo
"M A I N - M E N U"
18
tput sgr0
19
20
tput cup 7 15
21
echo
"1. User Management"
22
23
tput cup 8 15
24
echo
"2. Service Management"
25
26
tput cup 9 15
27
echo
"3. Process Management"
28
29
tput cup 10 15
30
echo
"4. Backup"
31
32
33
tput bold
34
tput cup 12 15
35
read
-p
"Enter your choice [1-4] "
choice
36
37
tput
clear
38
tput sgr0
39
tput rc
輸出:
3. setleds 命令
這個命令可以讓你控制鍵盤燈,例如打開數字鍵盤燈:
1
setleds -D +num
關閉數字鍵盤燈:
1
setleds -D -num
- -caps: 清除大寫燈
- +caps:打開大寫燈
- -scroll:清除滾動鎖
- +scroll:打開滾動鎖
4. zenity 命令
這個命令可以顯示GTK+的對話框,然後返回用戶的輸入。你可以用這個命令在腳本中顯示信息,並要求用戶輸入信息。下面這段代碼就是域名的whois查詢:
01
02
03
_zenity=
"/usr/bin/zenity"
04
_out=
"/tmp/whois.output.$$"
05
domain=$(${_zenity} --title
"Enter domain"
\
06
--entry --text
"Enter the domain you would like to see whois info"
)
07
08
if
[ $? -
eq
0 ]
09
then
10
11
whois $domain |
tee
>(${_zenity} --width=200 --height=100 \
12
--title=
"whois"
--progress \
13
--pulsate --text=
"Searching domain info..."
\
14
--auto-
kill
--auto-close \
15
--percentage=10) >${_out}
16
17
18
${_zenity} --width=800 --height=600 \
19
--title
"Whois info for $domain"
\
20
--text-info --filename=
"${_out}"
21
else
22
${_zenity} --error \
23
--text=
"No input provided"
24
fi
輸出: