shell 判断文件是否存在(csh bash)

文章目录

    • 前言
      • [1. -e 判断文件是否存在](#1. -e 判断文件是否存在)
      • [2. -f 判断文件是否存在且为普通文件](#2. -f 判断文件是否存在且为普通文件)
      • [3. -d 判断文件是否存在且为目录](#3. -d 判断文件是否存在且为目录)
      • [3. -s 判断文件是否存在且不为空](#3. -s 判断文件是否存在且不为空)
      • [4. -r 判断文件是否存在且可读](#4. -r 判断文件是否存在且可读)
      • [5. -w 判断文件是否存在且可写](#5. -w 判断文件是否存在且可写)
      • [6. -x 判断文件是否存在且可执行](#6. -x 判断文件是否存在且可执行)

前言

Shell 编程能提升我们工作效率,在 shell 中, 可以借助文件测试符号来判断一个文件是否存在。 常用的文件测试符号有 -e, -f, -d, -s, -r。

1. -e 判断文件是否存在

bash 复制代码
#!/bin/csh

set fileName = "test.txt"
#set fileName = "test_dir"

if (-e $fileName) then
  echo "$fileName" " is exit"
else
  echo "$fileName" " is not exit"
endif
bash 复制代码
#!/bin/bash

file=test.txt
#file=test_dir

if [ -e "$file" ]; then
  echo "$file" "is exit"
else
  echo "$file" "is not exit"
fi

2. -f 判断文件是否存在且为普通文件

3. -d 判断文件是否存在且为目录

bash 复制代码
#!/bin/csh

set fileName = "test_test"

if (-d $fileName) then
  echo "$fileName" " is exit"
else
  echo "$fileName" " is not exit"
endif

3. -s 判断文件是否存在且不为空

4. -r 判断文件是否存在且可读

5. -w 判断文件是否存在且可写

6. -x 判断文件是否存在且可执行

相关推荐
LongRunning1 小时前
【Linux】RK3568(三)操作-视频流
linux
Discipline~Hai1 小时前
Linux网络编程02-TCP协议
linux·网络·tcp/ip·嵌入式·linux网络编程
abc light2 小时前
Linux TCP网络
linux·网络·tcp/ip
Jason_zhao_MR2 小时前
电能质量监测为什么需要PTP精确时钟同步
linux·单片机·嵌入式硬件·嵌入式
视觉小萌新2 小时前
A1——基于AMD-48G显卡下载Gemma4模型
linux·ubuntu
不会就选b3 小时前
数据结构之栈的算法题(OJ)
linux·数据结构·算法
刘某的Cloud3 小时前
k8s部署prometheus架构规则
linux·运维·kubernetes·prometheus·监控
mounter6254 小时前
从 2026 LSFMM/BPF 峰会看 eBPF 生态演进:技术变革、工具全景与资源泄漏诊断实战
linux·linux kernel·kernel
M78佐菲4 小时前
Linux学习笔记:网络通信
linux·笔记·学习·算法
AAA代码批发商4 小时前
Days37 Linux C 网络编程:UDP、TCP 与 HTTP 协议实战详解
linux·c语言·网络