Shell之Test命令

目录

  • Shell之Test命令
    • 参考
    • Test简介
    • Test语法
    • 表达式之逻辑运算
    • 表达式之字符串判断
    • 表达式之整数判断
    • 表达式之文件判断

Shell之Test命令

Written by Zak Zhu

学习python风格, 优雅规范书写shell代码

参考

  • 鸟哥私房菜(http://cn.linux.vbird.org/linux_basic/0340bashshell-scripts_3.php)
  • Shell test命令 (Shell [])详解, 附带所有选项及说明(http://c.biancheng.net/view/2742.html)
  • shell中if语句的使用(https://www.cnblogs.com/aaronLinux/p/7074725.html)
  • 菜鸟教程/Shell test 命令(https://www.runoob.com/linux/linux-shell-test.html)

Test简介

shell中的test命令用于检查某个条件是否成立, 它可以进行整数, 字符串和文件三个方面的判断. test命令通常和if语句一起使用.

Test语法

test EXPRESSION
# 等价于
[ EXPRESSION ]

!! 语法注意:

  1. 中括号内的每个组件都用空格隔开
  2. 中括号内的变量用双引号包围起来

表达式之逻辑运算

  • 非运算

    [ ! EXPRESSION ]
  • 与运算

    [ EXPRESSION1 -a EXPRESSION2 ]
    # 等价于
    [ EXPRESSION1 ] && [ EXPRESSION2 ]
  • 或运算

    [ EXPRESSION1 -o EXPRESSION2 ]
    # 等价于
    [ EXPRESSION1 ] || [ EXPRESSION2 ]

表达式之字符串判断

表达式 注释
-z STRING the length of STRING is zero
STRING1 == STRING2
STRING1 != STRING2

表达式之整数判断

表达式 注释
INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is greater than to INTEGER2
INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is less than to INTEGER2

表达式之文件判断

1. 文件类型的判断

表达式 注释
-e FILE FILE exists
-d FILE FILE is a directory
-f FILE FILE is a regular file
-s FILE FILE has a size greater than zero
...

2. 文件权限的判断

表达式 注释
-r FILE FILE read permission is granted
-w FILE FILE write permission is granted
-x FILE FILE execute permission is granted
-u FILE FILE SUID bit is set
-g FILE FILE SGID bit is set
-k FILE FILE Sticky bit is set

3. 文件比较的判断

表达式 注释
FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers
FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2
FILE1 -ot FILE2 FILE1 is older than FILE2

你可能感兴趣的:(Shell之Test命令)