shell简单使用(-)判断
记几个判断相关的简单例子
1. 文件相关判断比较
#!/bin/bash
if [ $# -lt 1 ]thenecho "No file name"exit 1
elif [ -d $1 ]thenecho $1 is directory
elif [ -b $1 ]then echo $1 is block device
elif [ -h $1 ]thenecho $1 is link file
elif [ -c $1 ]thenecho $1 is character device
elif [ -f $1 ]thenecho $1 is normal file
else echo "Don't recognize $1"
fiif [ -r $1 ]thenecho $1 is can be read
fiif [ -w $1 ]then echo $1 is can be write
fiif [ -x $1 ]thenecho $1 is can be excute
fiif [ -u $1 ]thenecho $1 has SUID attribution
fiif [ -g $1 ]thenecho $1 has SGID attribution
fiif [ -k $1 ]thenecho $1 has Sticky bit attribution
fiif [ -s $1 ]thenecho $1 is a xxx
fiexit 0
执行结果如下:
2. 数字相关判断
a.
#!/bin/bashif [ "$1" -eq "$2" ]; then
# if [ "$1" -ne "$2" ]; thenecho $1 equal $2fiif [ "$1" -lt "$2" ]; then
# if [ "$1" -le "$2" ]; thenecho $1 less than $2
fiif [ "$1" -gt "$2" ]; then
# if [ "$1" -ge "$2" ]; thenecho $1 grate then $2
fi
b.
#!/bin/bashread -p "Input the age: " agecase $age in[0-9]|[1][0-2])echo "child";;[1][0-9])echo "young";;[2-5][0-9] )echo "adult";;[6-9][0-9]) echo "old";;* )echo "Not people";;
esac
exit 0
执行结果如下:
c.
#!/bin/bash
read -p "Iuput your birthday (MMDD.ex> 0709): " bir
now=`date +%m%d`
if [ "$bir" == "$now" ];thenecho "Happy birthday !!!"
elif [ "$bir" -gt "$now" ];thenyear=`date +%Y`total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))echo "Your birthday will be $total_d later"
elseyear=$((`date +%Y`+1))total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))echo "Your birthday will be $total_d later"
fi
执行结果如下:
3. 字符串比较
#!/bin/bashif [ "$1" == "$2" ]; then
# if [[ "$1" == "$2" ]]; thenecho $1 equal $2
fiif [ "$1" != "$2" ]; thenecho $1 no equal $2
fiif [[ "$1" > "$2" ]]; then
# if [ "$1" \> "$2" ]; thenecho $1 grate then $2
fiif [[ "$1" < "$2" ]]; then
# if [ "$1" \< "$2" ]; thenecho $1 less then $2
fiif [ -z "$1" ]; thenecho $1 is empty
fiif [ -n "$1" ]; thenecho $1 is no empty
fiif [[ "$1" == 1* ]]; thenecho $1 == "1*" 1111111111
fiif [[ "$1" == "1*" ]]; thenecho $1 == \"1*\" 2222222222
fi
执行结果如下:
两次对1*的比较,分别是模式匹配和全字符串匹配