Linux shell 脚本小记

if结构

 

#!/bin/env bash

if [ $1 -gt 0 ]
then
        echo "$1 is positive"
elif [ $1 -lt 0 ]
then
        echo "$1 is negative"
else
        echo "$1 is zero"
fi

 

while读取文件

while read aa
do
        echo "$aa"
done < aaa.s

 

数字比较

#等于
$num1 -eq $num2 
#不等于
$num1 -ne $num2
#小于
$num1 -lt $num2
#小于或等于
$num1 -le $num2
#大于
$num1 -gt $num2
#大于等于
$num1 -ge $num2

 

字符串比较

#字符串长度是否为0
-z $str
#字符串长度是否不为0
-n $str
#字符串是否相等
$str1 == $str2
#字符串是否不等
$str1 != $str2

 

使用举例:

if [ -z $str ]
then
        echo "string is empty"
elif [ -n $str ]
then
        echo "string not empty"
fi


[ -z $str ] && echo "yes" || echo "no"

//获取命令的结果方法一
ret=$([ -z $str ] && echo "yes" || echo "no")

//获取命令的结果方法二
ret1=`[ -z $str ] && echo "yes" || echo "no"`

echo "ret=$ret, ret1=$ret1"

 

文件比较

#文件名是否存在
-e $file
#是否是文件
-f $file
#是否是目录
-d $file
#是否是符号链接
-L $file
#文件是否可读
-r $file
#文件是否可写
-w $file
#文件是否可执行
-x $file

 

多个条件判断,即与、或

#与
if [ -e $file -a -f $file ]
then
        echo "$file is exists, and is file"
fi

#或
if [ $num -eq -1 -o $num -gt 0 ]
then
        echo "$num is ok"
fi

 

posted @ 2016-03-15 15:12  qingyezhu  阅读(155)  评论(0编辑  收藏  举报