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 判断文件是否存在且可执行

相关推荐
蜡台1 小时前
Python包管理工具pip完全指南-----2
linux·windows·python
Ujimatsu1 小时前
虚拟机安装Debian 13.x及其常用软件(2026.4)
linux·运维·ubuntu
千百元1 小时前
zookeeper启不来了
linux·zookeeper·debian
AnalogElectronic3 小时前
linux 测试网络和端口是否连通的命令详解
linux·网络·php
Edward111111114 小时前
4月28日防火墙问题
linux·运维·服务器
子琦啊4 小时前
【算法复习】字符串 | 两个底层直觉,吃透高频题
linux·运维·算法
AOwhisky5 小时前
Kubernetes 学习笔记:集群管理、命名空间与 Pod 基础
linux·运维·笔记·学习·云原生·kubernetes
小龙在慢慢变强..6 小时前
目录结构(FHS 标准)
linux·运维·服务器
2035去旅行6 小时前
嵌入式开发,如何选择C标准库
linux·arm开发
刘延林.6 小时前
win11系统下通过 WSL2 安装Ubuntu 24.04 使用RTX 5080 GPU
linux·运维·ubuntu