linux 中判断文件是否存在、是否为目录、文件、是否为空
001、判断文件是否存在
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -e a.txt ]; then echo "exist"; fi ## 判断文件是否存在 exist (base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -e b.txt ]; then echo "exist"; fi
也可以用:
a、
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -f a.txt ]; then echo "exist"; fi ## 判断是否为文件 exist (base) [root@PC1 test4]# if [ -f b.txt ]; then echo "exist"; fi
b、
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -d dir01 ]; then echo "exit"; fi ## 判断是否为目录 exit (base) [root@PC1 test4]# if [ -d dir02 ]; then echo "exit"; fi
002、判断是否为文件
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -f a.txt ]; then echo "file"; fi ## 判断是否为目录 file (base) [root@PC1 test4]# if [ -f dir01 ]; then echo "file"; fi
003、判断是否为目录
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# if [ -d a.txt ]; then echo "dir"; fi ## 判断是否为目录 (base) [root@PC1 test4]# if [ -d dir01 ]; then echo "dir"; fi dir
004、判断文件是否不为空
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# cat a.txt (base) [root@PC1 test4]# if [ -s a.txt ]; then echo "no empty"; fi ## 判断文件是否不为空 (base) [root@PC1 test4]# echo "xxx" > a.txt (base) [root@PC1 test4]# if [ -s a.txt ]; then echo "no empty"; fi no empty
005、判断目录是否为空
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# ls -A dir01/ (base) [root@PC1 test4]# if find ./ -mindepth 1 -maxdepth 1 -type d -empty | grep "." &> /dev/null; then echo "empty"; fi empty ## 判断目录是否为空 (base) [root@PC1 test4]# seq 10 > dir01/x.txt (base) [root@PC1 test4]# if find ./ -mindepth 1 -maxdepth 1 -type d -empty | grep "." &> /dev/null; then echo "empty"; fi
判断目录是否为空:
(base) [root@PC1 test4]# ls a.txt dir01 (base) [root@PC1 test4]# ls -A dir01/ (base) [root@PC1 test4]# if ! ls -A dir01/ | grep -q "."; then echo "empty"; fi empty ## 判断目录是否空 (base) [root@PC1 test4]# seq 10 > dir01/x.txt (base) [root@PC1 test4]# ls -A dir01/ x.txt (base) [root@PC1 test4]# if ! ls -A dir01/ | grep -q "."; then echo "empty"; fi
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2022-05-31 python中实现文本大小写的转换
2022-05-31 python中统计文本的行数及列数
2022-05-31 python 中提取以指定字符开头或指定字符结尾的数据
2022-05-31 python 中从文本中提取包含指定字符的数据
2022-05-31 linux中设置系统时间
2022-05-31 X86、AMD64、X86_64、X64的区别
2022-05-31 redhat9中配置yum仓库