Linux Shell脚本 之 条件判断

首先想到的就是if else条件判断语句了,下面给出一个全面的语句:

 if condition
 then
     condition is true
     execute all commands up to elif statement
 elif condition1 
 then
     condition1 is true
     execute all commands up to elif statement  
 elif condition2
 then
     condition2 is true
     execute all commands up to elif statement          
 elif conditionN
 then
     conditionN is true
     execute all commands up to else statement          
 else
     None of the above conditions are true
     execute all commands up to fi
 fi

这里的condition就是用来测试的条件,大概有以下几种表现形式:

if test var == value

if test "$pass" = "tom"

if test -f /file/exists 判断某个文件是否存在

if [ $n -gt 0 ]

if [ -f /etc/resolv.conf ]

if [ -z $Str ] 判断字符串是否为空(字符串长度为0)

数值比较时,还可以用以下符号:

if test $n -eq 10 等于
if test $n -ge 10 大于等于
if test $n -gt 20 大于
if test $n -le 6  小于等于
if test $n -lt 0  小于
if test $n -ne -1 不等于

假如要判断一个程序执行是否正常退出:

#!/bin/bash

date
status=$?

if test status eq 0 
then 
    echo "执行成功"
else 
    echo "执行失败"
fi

$?能获取程序执行的返回值,一般0表示成功,其他的都是失败了。那么和$?类似的还有:

$* 获取执行命令的所有参数,分隔符以系统设置为准.
$@ 获取执行命令的所有参数,且以空格分隔.
$# holds the number of positional parameters.
$- holds flags supplied to the shell.
$$ holds the process number of the shell (current shell).
$! hold the process number of the last background command.

对文件的判断汇总如下:

[ -a /etc/resolv.conf ] 文件是否存在
[ -e /tmp/test.txt ]    文件是否存在
[ -b /dev/zero ] 文件存在,并且是个block special file
[ -c /dev/tty0  ] 文件存在,并且是个character special file
[ -d "$DEST" ] 文件夹存在
[ -f /path/to/file ] 文件存在,且是个普通文件
[ -u /path/to/file] 文件存在,且set-user-id is set
[ -g /path/to/file] 文件存在,且set-group-id is set
[ -h /path/to/file] 文件存在,且是一个symbolic link
[ -k /path/to/file] 文件存在,且sticky位被设置过
[ -p /path/to/file] 文件存在,且是一个named pipe (FIFO)
[ -r /path/to/file] 文件存在,且是个只读文件
[ -w /path/to/file] 文件存在,且文件可写
[ -x /path/to/file] 文件存在,且可执行
[ -s /path/to/file] 文件存在,且文件大小大于0 [ -t /path/to/file] True if file descriptor fd is open and refers to a terminal
[
-O /path/to/file] True if file exists and is owned by the effective user id
[
-G /path/to/file] True if file exists and is owned by the effective group id
[
-L /path/to/file] True if file exists and is a symbolic link
[
-S /path/to/file] True if file exists and is a socket
[
-N /path/to/file] True if file exists and has been modified since it was last read.

最后做个小的总结,总体上来看条件判断分为整数比较、字符串比较以及文件的比较,文件的比较条件虽然比较多,但是常用的可能不会很多,而且很多比较符号的字母就能看出其比较的含义。

原文地址:https://www.cnblogs.com/bluejavababy/p/5047494.html