shell脚本if表达式

发布于 分类 Linux

无论什么编程语言都离不开条件判断。SHELL也不例外。
大体的格式如下:
if list then
do something here
elif list then
do another thing here
else
do something else here
fi

一个例子:

#!/bin/sh
SYSTEM=`uname -s`    # 获取操作系统类型,我本地是linux
if [ $SYSTEM ="Linux" ] ; then    # 如果是linux话输出linux字符串
  echo"Linux"
elif [ $SYSTEM ="FreeBSD" ] ; then 
  echo"FreeBSD"
elif [ $SYSTEM ="Solaris" ] ; then
  echo"Solaris"
else
  echo"What?"
fi    # 判断结束,以fi结尾

基本上和其他脚本语言一样。没有太大区别。

判断操作符 判断为真的条件
字符串判断  
[ stringA=stringB ] stringA等于stringB
[ stringA==stringB ] stringA等于stringB
[ stringA!=stringB ] stringA不等于stringB
[ string ] string不为空
[ -z string ] string长度为0
[ -n string ] string长度不为0
逻辑判断  
[ stringA -a stringB ] stringA和stringB都是真
[ stringA -o stringB ] stringA或stringB是真
[ !string ] string不为真
逻辑判断(复合判断)  
[[ pattern1 && pattern2 ]] pattern1和pattern2都是真
[[ pattern1 || pattern2 ] pattern1或pattern2是真
[[ !pattern ]] pattern不为真
整数判断  
[ intA -eq intB ] intA等于intB
[ intA -ne intB ] intA不等于intB
[ intA -gt intB ] intA大于intB
[ intA -ge intB ] intA大于等于intB
[ intA -lt intB ] intA小于intB
[ intA -le intB ] intA小于等于intB
文件判断中的二进制操作  
[ fileA -nt fileB ] fileA比fileB新
[ fileA -ot fileB ] fileA比fileB旧
[ fileA -ef fileB ] fileA和fileB有相同的设备或者inode值
文件检验  
[ -d $file ] or [[ -d $file ]] file为目录且存在时为真
[ -e $file ] or [[ -e $file ]] file为文件且存在时为真
[ -f $file ] or [[ -f $file ]] file为非目录普通文件存在时为真
[ -s $file ] or [[ -s $file ]] file文件存在, 且长度不为0时为真
[ -L $file ] or [[ -L $file ]] file为链接符且存在时为真
[ -r $file ] or [[ -r $file ]] file文件存在且可读时为真
[ -w $file ] or [[ -w $file ]] file文件存在且可写时为真
[ -x $file ] or [[ -x $file ]] file文件存在且可执行时为真

语法虽然简单,但是在SHELL里使用的时候,它可以实现强大的功能或执行逻辑。

再来一个[[]]的例子

function confirm(){
    confirm=""
    read -p"Is this ok [y/N]:" confirm
    #if ["$confirm" !="y" ]; then
    #if ["$confirm" = y -o"$confirm" = Y ]; then
    if [[ $confirm != [yY]* ]]; then
        exit 1
    fi
}

-- The End --

本文标题: shell脚本if表达式

本文地址: https://seonoco.com/blog/shell-script-if-expression

本页面显示内容已针对移动端进行优化,点击查看完整版本