#!/bin/bash
LOG_DIR=/var/log
ROOT_UID=0
LINES=50
E_XCD=66
E_NOTROOT=67
if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root to run the script"
exit $E_NOTROOT
fi
if [ -n "$1" ]
then
lines=$1
else
lines=$LINES
fi
cd $LOG_DIR
if ['pwd' != "$LOG_DIR" ]
then
echo "Can not change to $LOG_DIR."
exit $E_XCD
fi
tail -$lines messages > mesg.temp
mv mesg.temp messages
cat /dev/null > wtmp
echo "Logs cleaned up.";
exit 0
有时候,如果想参数化子程序,可以这样写
#!/bin/bash
W_WRONG_ARGS=65
script_param="-a -h -m -z"
number_of_expected_args=3
if [ $# -ne $number_of_expected_args ]
then
echo "Usage: 'basename $0' $script_param"
exit $W_WRONG_ARGS
fi
字符串比较时,引用变量记得加上引号,不然可能由于变量中的空格导致Too many arguments错误
#!/bin/sh
myvar="foo bar oni"
if [ "$myvar" = "foo bar oni" ]; then
echo "yes"
fi
打印出指定目录下所有文件和目录
#!/bin/bash
for myfile in `find /etc/`
do
if [ -d "$myfile" ]
then
echo "${myfile}(dir)"
else
echo "${myfile}"
fi
done
引用参数
#!/bin/bash
for x in "$@"
do
echo "you typed $x"
done
计算出1-100的和
#!/bin/bash
sum=0
i=1
while [ $i -lt 100 ]
do
sum=$(( $sum + $i ))
i=$(( $i + 1 ))
done
echo "SUM=${sum}"
case in语句
#!/bin/bash
if [ ! -n $1 ]; then
echo "Usage: `basename $0` filename"
fi
case "${1##*.}" in
gz)
echo "压缩文件"
;;
txt)
echo "文本文件"
;;
sh)
echo "bash 脚本文件"
;;
*)
echo "其他文件"
;;
esac