shell if 条件判断 文件 文件夹 链接

来源:互联网 发布:农村淘宝小二待遇如何 编辑:程序博客网 时间:2024/05/11 21:49
Linux的参数总是太多记不住:
  • –b 当file存在并且是块文件时返回真
  • -c 当file存在并且是字符文件时返回真
  • -d 当pathname存在并且是一个目录时返回真
  • -e 当pathname指定的文件或目录存在时返回真
  • -f 当file存在并且是正规文件时返回真
  • -g 当由pathname指定的文件或目录存在并且设置了SGID位时返回为真
  • -h 当file存在并且是符号链接文件时返回真,该选项在一些老系统上无效
  • -k 当由pathname指定的文件或目录存在并且设置了“粘滞”位时返回真
  • -p 当file存在并且是命令管道时返回为真
  • -r 当由pathname指定的文件或目录存在并且可读时返回为真
  • -s 当file存在文件大小大于0时返回真
  • -u 当由pathname指定的文件或目录存在并且设置了SUID位时返回真
  • -w 当由pathname指定的文件或目录存在并且可执行时返回真。一个目录为了它的内容被访问必然是可执行的。
  • -o 当由pathname指定的文件或目录存在并且被子当前进程的有效用户ID所指定的用户拥有时返回真。

Bash Shell 里面比较字符写法:

  • -eq 等于
  • -ne 不等于
  • -gt 大于
  • -lt 小于
  • -le 小于等于
  • -ge 大于等于
  • -z 空串
  • = 两个字符相等
  • != 两个字符不等
  • -n 非空串

临时写个脚本把关注的判断写出来:
-----------------------------------------------------------------
#!/bin/bash

option="-a -b -c -d -e -f -g -h -k -p -r -s -u -w -o"
target="/tmp/file /tmp/link /tmp/dir"

mkEnv(){
        touch /tmp/file
        ln -s /tmp/ /tmp/link
        mkdir /tmp/dir
}

for op in ${option}
do
echo '---------------'
for tg in ${target}
do
echo -n "${op} , ${tg}"
test ${op} ${tg}
if [ ${?} -eq 0 ];then
echo -e  "\t\e[0;32mTrue\e[m"
else
echo -e "\t\e[0;31mFalse\e[m"
fi
        done
done
echo '---------------'
-----------------------------------------------------------------
-e , /tmp/file    True
-e , /tmp/link    True
-e , /tmp/dir    True
-d , /tmp/file    False
-d , /tmp/link    True
-d , /tmp/dir    True
-f , /tmp/file    True
-f , /tmp/link    False
-f , /tmp/dir    False
-s , /tmp/file    False
-s , /tmp/link    True
-s , /tmp/dir    True
-a , /tmp/file    True
-a , /tmp/link    True
-a , /tmp/dir    True
……

OK!  稍修改一下把关注的条件和结果判断一下吧


原文地址:http://hi.baidu.com/higkoo/item/c1623824fec428cba5275ade

原创粉丝点击