Write by lyc at 2018-10-18
Update by lyc at 2021-3-18:整理自己早期的word版本到markdown
一、shell if条件语句
1.shell if语法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| if <条件表达式>;then command fi
if <条件表达式>;then command else command fi
if <条件表达式>;then command elif <条件表达式>;then command else command fi
|
实例
1 2 3 4 5 6 7 8 9
| $ cat test.sh #!/bin/bash a=5 if [ $a -lt 10 ];then echo "sucess" else echo "false" fi
|
1 2 3 4 5 6 7 8 9
| $ cat test.sh #!/bin/bash a=5 if [[ "$a" -lt 10 ]];then echo "sucess" else echo "false" fi
|
二、判断字符串长度是否为0
方法1:-z -n
1 2 3 4
| $ [ -z "helloworld" ] && echo true || echo false false $ [ -n "helloworld" ] && echo true || echo false true
|
方法2:变量子串
${#char}
变量子串
1 2 3
| $ char=helloworld $ [ ${#char} -eq 0 ] && echo 1 || echo 0 0
|
方法3:expr length
1 2
| $ [ `expr length "helloworld"` -eq 0 ] && echo 1 || echo 0 0
|
方法4:wc -L
1 2
| $ [ `echo helloworld | wc -L` -eq 0 ] && echo 1 || echo 0 0
|
方法5:awk length
1 2
| $ [ `echo helloworld | awk '{print length}'` -eq 0 ] && echo 1 || echo 0 0
|
三、判断字符串是否为整数
方法1:删除一个字符串的所有数字,若长度为0,表示是整数,若不为0表示不是整数
1 2 3 4 5 6 7 8 9 10 11
| $ [ -n "`echo "helloworld123" | sed 's#[0-9]##g'`" ] && echo true || echo false true $ [ -n "`echo "123456" | sed 's#[0-9]##g'`" ] && echo true || echo false false
$ [ -z "`echo "helloworld123" | sed 's#[0-9]##g'`" ] && echo true || echo false false $ [ -z "`echo "123456" | sed 's#[0-9]##g'`" ] && echo true || echo false true
|
方法2:使用变量子串来替换数字为空
1 2 3 4 5 6
| $ num=helloworld123 $ [ -n "${num//[1-9]/}" ]&&echo char||echo int char $ num=123456 $ [ -n "${num//[1-9]/}" ]&&echo char||echo int int
|
方法3:使用expr计算后返回值是否为0来判断(推荐)
1 2 3 4 5 6 7 8 9
| $ expr "helloworld123" + 1 &>/dev/null $ echo $? 2 $ expr 123 + 1 &>/dev/null $ echo $? 0 $ expr 0 + 0 &>/dev/null $ echo $? 1
|
方法4:使用123|bc,返回值为123来判断整数
1 2 3 4 5 6 7 8
| $ echo helloworld123|bc 0 $ echo helloworld|bc 0 $ echo 123|bc 123 $ echo 0|bc 0
|