1.使用seq命令产生循环参数
#! /bin/sh
echo
for a in `seq 80`
do
echo -n "$a "
done
echo;echo
COUNT=80
for a in `seq $COUNT`
do
echo -n "$a "
done
echo;echo
BEGIN=75
END=80
for a in `seq $BEGIN $END`
do
echo -n "$a "
done
echo;echo
BEGIN=45
INTERVAL=5
END=80
for a in `seq $BEGIN $INTERVAL $END`
do
echo -n "$a "
done
echo;echo
exit 0
2.字母统计
#! /bin/sh
MINARGS=2
E_BADARGS=65
FILE=$1
let LETTERS=$#-1
show_help(){
echo
echo Usage: `basename $0` file letters
echo Note: `basename $0` arguments are case sensitive.
echo Example: `basename $0` foobar.txt G n U L i N U x.
echo
}
if [ $# -lt $MINARGS ]
then
echo
echo "Not enough arguments."
echo
show_help
exit $E_BADARGS
fi
if [ ! -f $FILE ]
then
echo "File /"$FILE/" does not exist."
exit $E_BADARGS
fi
for n in `seq $LETTERS`
do
shift
if [[ `echo -n "$1" | wc -c` -eq 1 ]]
then
echo "$1" -/> `cat $FILE | tr -cd "$1" | wc -c` ------tr -cd "$1"以字节为单位删除除$1以外的所有字符
else
echo "$1 is not a single char."
fi
done
exit $?
3.使用getopt来分析命令行选项
#! /bin/sh
E_OPTERR=65
if [ "$#" -eq 0 ]
then
echo "Usage $0 -[options a,b,c]"
exit $E_OPTERR
fi
set -- `getopt "abcd:" "$@"`
while [ ! -z "$1" ]
do
case "$1" in
-a) echo "Option /"a/"";;
-b) echo "Option /"b/"";;
-c) echo "Option /"c/"";;
-d) echo "Option /"d/"";;
*) break;;
esac
shift
done
exit 0
4.记录按键
#! /bin/sh
keypresses=4
old_tty_setting=$(stty -g)
echo "Press $keypresses keys."
stty -icanon -echo
keys=$(dd bs=1 count=$keypresses 2>/dev/null)
stty "$old_tty_setting"
echo "You pressed the /"$keys/" keys."
exit 0
5.安全的删除一个文件
#! /bin/sh
PASSES=7
BLOCKSIZE=1
E_BADARGS=70
E_NOT_FOUND=71
E_CHANGED_MIND=72
if [ -z "$1" ]
then
echo "Usage: `basename $0` filename"
exit $E_BADARGS
fi
file=$1
if [ ! -e "$file" ]
then
echo "File /"file/" not found."
exit $E_NOT_FOUND
fi
echo;echo -n "Are you absolutely sure you want to blot out /"$file/" (y/n)?"
read answer
case "$answer" in
[nN]) echo "Changed your mind,huh?"
exit $E_CHANGED_MIND
;;
*) echo "Blotting out file /"$file/".";;
esac
flength=$(ls -l "$file" | awk '{print $5}')
pass_count=1
chmod u+w "$file"
echo
while [ "$pass_count" -le "$PASSES" ]
do
echo "Pass #$pass_count"
sync -----------sync:把缓存数据写入磁盘
dd if=/dev/zero of=$file bs=$BLOCKSIZE count=$flength ----------- 按block块删除
sync
dd if=/dev/zero of=$file bs=$BLOCKSIZE count=$flength
let "pass_count += 1"
echo
done
rm -f $file
sync
echo "File /"$file/" blotted out and deleted.";echo
exit 0
6.文件名产生器
#! /bin/sh
BASE_STR=`mcookie`
POS=11
LEN=5
prefix=temp
suffix=${BASE_STR:POS:LEN} --------提取从第11个字符之后的长度为5的字符串
temp_filename=$prefix.$suffix
echo "Temp filename = "$temp_filename""
exit 0
7.使用m4(m4宏处理)
#! /bin/sh
string=abcdA01
echo "len($string)" | m4
echo "substr($string,4)" | m4
echo "regexp($string,[0-1][0-1],/&Z)" | m4
echo "incr(22)" | m4
echo "eval(99 / 3)" | m4
exit 0