linux脚本-结构化命令

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wilder_ting/article/details/78937049
  1. 根据条件从而跳过某些命令.其语法格式为:
    if command
    then
    command
    fi#结束语句
    如果command命令的状态运行码为0,那么将会执行then后面的语句,否则将不会执行.
  2. if-else-then语句,语法格式为:
    if command
    then
    command
    else
    command
    fi
    另外一种形式为:
    if command1
    then
    commands
    elif commands
    then
    more commands
    fi
    如果状态执行码为0,那么就会执行then后面的命令.如果状态执行码为正数,那么就会跳转到elif语句.继而判断command命令执行后的状态执行码,若为0,则执行then后面的命令.
  3. test命令:test命令测试会返回状态执行码.语法格式为test condition.在if-else语句中使用test命令,其语法格式如下:
    if test condition
    then
    command
    fi
    看如下代码,
    #!/bin/bash
    my_variable=”Full”
    if test myvariablethenechothe my_variable expression returns a True”
    else
    echo “the $my_variable expression return a False”
    fi
    test命令可以用在三类比较中,数值比较,字符串比较,文件比较.
    • 数值比较:
比较 描述
n1 -eq n2 检查n1是否等于n2
n1 -ge n2 检查n1是否大于或者等于n2
n1 -gt n2 检查n1是否大于n2
n1 -le n2 检查n1是否小于或者等于n2
n1 -lt n2 检查n1是否小于n2
n1 -ne n2 检查n1是否不等于n2

- 字符串比较:
- | 比较 | 描述 |
|——–|——–|
|str1 =str2 | 检查str1和str2是否相等|
|str1 != str2 |检查str1与str2不同 |
| str1 < str2|检查str1是否比str2小|
|str1 > str2|检查str1是否比str2大|
|-n str|检查str的长度是否非0|
|-z str|检查str的长度是否为0|
在使用大小比较时,需要对>和<进行转义,不然会当成重定向输出.
- 文件比较

比较 描述
-d file 检查文件是否存在并是一个目录
-e file 检查文件是否存在
-f file 检查file是否存在并是一个文件
-r file 检查file是否存在并可读
-s file 检查file是否存在并非空
-w file 检查file是否存在并可写
-x file 检查file是否存在并可执行

看如下代码:
if [ -e location]thenechoOKonthe location directory”
echo “Now checking on the file , filenameif[e location/ filename]thenechoOKonthefilenameechoUpdatingCurrentDatedate>> location/ filenameelseechoFiledoesnotexistechoNothingtoupdatefielseechoThe location directory does not exist”
echo “Nothing to update”
fi
3. 符合条件测试:其命令格式为:
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
4.case命令:其命令格式为:
case variable in
pattern1|pattern2)command;;
pattern3) command;;
pattern) command;;
default command;;
esac
看以下代码:
#!/bin/bash
#using the case command
case USERinctw|barbara)echoWelcome, USER”
echo “Please enjoy your visit”;;
testing)
echo “Special testing account”;;
jessai)
echo “Do not forget to log off when you’re done”;;
*)
echo “Sorry,you’re not allowed here”;;
esac
5. if-else高级特性:
- 使用双括号:其格式为(( expression )),双括号中的大于小于符号不需要进行转义
- 使用双方括号:[[ expression ]],针对于字符串比较.

猜你喜欢

转载自blog.csdn.net/Wilder_ting/article/details/78937049