linux shell中if的各种判断

2019-09-23 08:52:58王旭

INTEGER1-le INTEGER2
INTEGER1is less than or equal to INTEGER2
INTEGER1-lt INTEGER2
INTEGER1is less than INTEGER2
INTEGER1-ne INTEGER2
INTEGER1is not equal to INTEGER2
FILE1-nt FILE2
FILE1is newer (modification date) than FILE2
FILE1-ot FILE2
FILE1is older than FILE2
-bFILE
FILEexists and is block special
-cFILE
FILEexists and is character special
-dFILE
FILEexists and is a directory
-eFILE
FILEexists 文件存在
-fFILE
FILEexists and is a regular file 文件存在且是普通文件
-hFILE
FILEexists and is a symbolic link (same as -L)
-LFILE
FILEexists and is a symbolic link (same as -h)
-GFILE
FILEexists and is owned by the effective group ID
-OFILE
FILEexists and is owned by the effective user ID
-pFILE
FILEexists and is a named pipe

-sFILE
FILEexists and has a size greater than zero
-SFILE
FILEexists and is a socket
-wFILE
FILEexists and is writable
-xFILE
FILEexists and is executable

if简化语句

最常用的简化if语句
&&如果是“前面”,则“后面”
[ -f/var/run/dhcpd.pid ] && rm /var/run/dhcpd.pid 检查文件是否存在,如果存在就删掉
|| 如果不是“前面”,则后面
[ -f/usr/sbin/dhcpd ] || exit 0 检验文件是否存在,如果存在就退出

用简化 if和$1,$2,$3来检测参数,不合理就调用help
[ -z"$1" ] && help 如果第一个参数不存在(-z 字符串长度为0 )
[ "$1"= "-h" ] && help 如果第一个参数是-h,就显示help

例子
#!/bin/sh
[ -f"/etc/sysconfig/network-scripts/ifcfg-eth0" ] && rm-f /etc/sysconfig/network-scripts/ifcfg-eth0
cpifcfg-eth0.bridge /etc/sysconfig/network-scripts/ifcfg-eth0
[ -f"/etc/sysconfig/network-scripts/ifcfg-eth1" ] && rm-f /etc/sysconfig/network-scripts/ifcfg-eth1
cpifcfg-eth1.bridge /etc/sysconfig/network-scripts/ifcfg-eth1
[ -f"/etc/sysconfig/network-scripts/ifcfg-eth0:1" ] &&rm -f /etc/sysconfig/network-scripts/ifcfg-eth0:1