| 关键词:echo 文件 测试 file passwd etc shellFiles kingdom python odysee |
谈一谈关于shell编程中的文件测试 Shell编程有时处理一个对象时,需要我们对对象进行测试。 只有符合要求的才采取下一步操作,这样做的好处可以避免程序出错。 这个测试的对象可以是文件、字符串、数字等等。 下面我们来简单的看一下对于文件的测试。 1、 文件测试 格式: [ 操作符 文件目录 ] 常用操作符: -d 测试是否为一个目录 -e 测试一个文件是否存在 -s 测试文件是否存在且长度不为0 -f 测试是否为一个普通文件 -r 测试文件是否存在且对于当前用户可读 -w 测试文件是否存在且对于当前用户可写 -x 测试文件是否存在且对于当前用户可执行 -L 测试文件是否存在且为链接文件 案例: (1) 、-f参数使用 //简单的使用&& 和 || [ -f /etc/passwd ] && echo "I am file" || echo "not file" I am file [ -f /etc ] && echo "I am file" || echo "not file" not file (2) 、-d参数使用 [odysee@kingdom shellFiles]$ [ -d /etc ] && echo "I am dir" || echo "not dir" I am dir (3) 、-e参数使用 [odysee@kingdom shellFiles]$ [ -e /etc/passwd ] && echo "yes" || echo "no" yes [odysee@kingdom shellFiles]$ [ -e /etc/passwds ] && echo "yes" || echo "no" no (4) 、-r -w -x 使用 [ -r /etc/passwd ] && echo "yes" || echo "no" yes [ -w /etc/passwd ] && echo "yes" || echo "no" no [ -x /etc/passwd ] && echo "yes" || echo "no" no //查看文件权限,很明显只有r权限 ll /etc/passwd -rw-r--r-- 1 root root 1490 Jan 25 09:53 /etc/passwd (5) 、-L参数使用 [odysee@kingdom shellFiles]$ which python2 /usr/bin/python2 [odysee@kingdom shellFiles]$ ll /usr/bin/python2 lrwxrwxrwx 1 root root 6 Aug 24 2017 /usr/bin/python2 -> python [odysee@kingdom shellFiles]$ [ -L /usr/bin/python2 ] && echo "yes" || echo "no" yes 补充: !:求反 //对-f /etc/passwd求反,即把true变为false //false则打印|| [ ! -f /etc/passwd ] && echo "I am not file" || echo "file" file //对-f /etc求反,即把false变为true //true则打印&& [ ! -f /etc ] && echo "I am not file" || echo "file" I am not file 测试完成 欢迎大家给予宝贵的意见或者建议。 欢迎大家补充或者共享一些其他的方法。 感谢支持。 |
| 本文出处: https://www.toutiao.com/a6658445016563712524/ |
|
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除
|