1. A yes/no dialog box
dialog --common-options --yesno text height width
e.g.
dialog --title "Confirm Infomation" --yesno "Are you sure to continue?" 7 60
(我想到,利用Linux C和shell混合编程能够比较容易得作到和用户经过这种dialog交互。好比Linux 程序须要用户输入,能够调用shell中的dialog命令,获取用户输入,而后将结果返回给shell
主进程。这避免了利用GTK或者QT编程的麻烦。回想学校里的BBS客户端TERM,彻底就是在控制台下跑的,既能够查看贴子,又能够回复,发帖,发邮件,真的很强大。若是在和用户的交互中编程
没有多媒体信息的话,利用这种方式已经足够了。另外,这种程序的移植性很是高。只要是支持标准c库、支持shell的Linux平台,均可以跑这种程序。)bash
2. 得到文件或者目录的绝对路径
root@localhost :/home/James/mypro/shell# ./getrealpath.sh menu.sh TryOut/ ../Linux-Pro/pipe/test.c
menu.sh -- /home/James/mypro/shellmenu.sh
TryOut/ -- /home/James/mypro/shell/TryOut
../Linux-Pro/pipe/test.c -- /home/James/mypro/Linux-Pro/pipetest.capp
#!/bin/bash #get realpath of a file or a directory #getrealpath filename1 dirname1 .... #realpath() takes one para, that is a file name or a dirctory name realpath() { name=$1 if [ -d $name ]; then old_pwd=$(pwd) cd $name new_pwd=$(pwd) cd $old_pwd echo $new_pwd fi if [ -f $name ]; then base=$(basename $name) dir=$(dirname $name) old_pwd=$(pwd) cd $dir new_pwd=$(pwd) new_name=$new_pwd$base cd $old_pwd echo $new_name fi } for file in $@; do real_path=$(realpath $file) echo "${file} -- ${real_path}" done
3. Input Dialog Box
dialog --title "PASSWORD" --inputbox "Enter your password " 8 60 2>/dev/null
(注意最后的2>/dev/null,它的做用是将标准错误输出重定向到/dev/null,若是没有这句话,2将会被默认输出到标准输出上,产生奇怪的现象。
因而可知,inputbox是经过标准错误输出来传回信息的。虽然有点取巧,可是应用起来很方便。Good!)spa
4. 得到用户密码(若是要回显*号的话,加上--insecure选项)
.net
#!/bin/bash # a sample file to read user's password # password storage data=$(tempfile 2>/dev/null) #trap signals trap 'rm -f $data' 0 1 2 5 15 # the 0 signal is trapped so that the temp file will be automatically removed when the script exits successfully #get passwd dialog --title "Password" \ --clear \ --passwordbox "Enter Your Password" 10 30 2>$data ret=$? #make decision case $ret in 0) echo "Password is $(cat $data)";; 1) echo "Cancel pressed.";; 255) [ -s $data ] && cat $data || echo "ESC pressed.";;#if size of $data is not zero, print out $data's content#!/bin/bash esac
5. 如何在脚本中创建临时文件,而且能自动清除?
如上例,tmpfilename=$(tempfile 2>/dev/null) #将错误输出重定向到/dev/null中,以避免影响结果。
trap 'rm -f $tmpfilename' 0 1 ..
那么此时程序正常退出的时候,或者exit 1的时候,都会清除临时文件。code
6. 打印一个棋盘
进程
#!/bin/bash ###print out a chess board for ((i=1; i<=8; i++)); do for ((j=1; j<=8; j++)); do total=$(($i+$j)) tmp=$((total%2)) if [ $tmp -eq 0 ]; then echo -e -n "\033[47m \033[0m" else echo -e -n "\033[40m \033[0m" fi done echo "" done
(放上此实例是为了从此写Linux C语言和Shell混合编程作准备)ip
7. 得到当前terminal的名字
tty
ci