您的位置:首页 > 运维架构 > Shell

shell简单使用(-)判断

2016-05-01 13:39 603 查看
记几个判断相关的简单例子

1. 文件相关判断比较

#!/bin/bash
if [ $# -lt 1 ]
then
echo "No file name"
exit 1
elif [ -d $1 ]
then
echo $1 is directory
elif [ -b $1 ]
then
echo $1 is block device
elif [ -h $1 ]
then
echo $1 is link file
elif [ -c $1 ]
then
echo $1 is character device
elif [ -f $1 ]
then
echo $1 is normal file
else
echo "Don't recognize $1"
fi

if [ -r $1 ]
then
echo $1 is can be read
fi

if [ -w $1 ]
then
echo $1 is can be write
fi

if [ -x $1 ]
then
echo $1 is can be excute
fi

if [ -u $1 ]
then
echo $1 has SUID attribution
fi

if [ -g $1 ]
then
echo $1 has SGID attribution
fi

if [ -k $1 ]
then
echo $1 has Sticky bit attribution
fi

if [ -s $1 ]
then
echo $1 is a xxx
fi

exit 0


执行结果如下:



2. 数字相关判断

a.

#!/bin/bash

if [ "$1" -eq "$2" ]; then
# if [ "$1" -ne "$2" ]; then
echo $1 equal $2

fi

if [ "$1" -lt "$2" ]; then
# if [ "$1" -le "$2" ]; then
echo $1 less than $2
fi

if [ "$1" -gt "$2" ]; then
# if [ "$1" -ge "$2" ]; then
echo $1 grate then $2
fi




b.

#!/bin/bash

read -p "Input the age: " age

case $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


执行结果如下:



b.

#!/bin/bash

read -p "Iuput your birthday (MMDD.ex> 0709): " bir
now=`date +%m%d`

if [ "$bir" == "$now" ];then
  echo "Happy birthday !!!"
elif [ "$bir" -gt "$now" ];then
  year=`date +%Y`
  total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))
  echo "Your birthday will be $total_d later"
else
  year=$((`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/bash

if [ "$1" == "$2" ]; then
# if [[ "$1" == "$2" ]]; then
echo $1 equal $2
fi

if [ "$1" != "$2" ]; then
echo $1 no equal $2
fi

if [[ "$1" > "$2" ]]; then
# if [ "$1" \> "$2" ]; then
echo $1 grate then $2
fi

if [[ "$1" < "$2" ]]; then
# if [ "$1" \< "$2" ]; then
echo $1 less then $2
fi

if [ -z "$1" ]; then
echo $1 is empty
fi

if [ -n "$1" ]; then
echo $1 is no empty
fi

if [[ "$1" == 1* ]]; then
echo $1 ==  "1*" 1111111111
fi

if [[ "$1" == "1*" ]]; then
echo $1 == \"1*\" 2222222222
fi


执行结果如下:



两次对1*的比较,分别是模式匹配和全字符串匹配
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: