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

相关推荐
拾贰_C16 小时前
【python | installation 】python 安装 | Windows | 命令使用
linux·数据库·ubuntu
无限进步_16 小时前
Linux进程终止——退出码、exit与_exit
linux·运维·服务器
编程大师哥16 小时前
最高效的 IO 并发方案
linux·网络·python
炘爚16 小时前
phase1:基础框架——编译 + MySQL + 登录/注册
linux·c++
小蜗子16 小时前
Windows 11 + RTX 5060 + WSL2 Ubuntu + NVIDIA DGL 容器
linux·运维·ubuntu
着迷不白17 小时前
八、shell脚本
linux·运维
爱装代码的小瓶子17 小时前
3. 设计buffer模块
linux·服务器·开发语言·c++·php
流浪00117 小时前
Linux系统篇(四):一文吃透 Linux 虚拟地址空间:从页表映射到内核结构体全链路拆解
linux·运维·服务器
Jacob程序员17 小时前
WebSSH技术实现全解析
linux·运维·服务器·websocket
暗冰ཏོ17 小时前
运维岗位完整学习指南:从 Linux 基础到 DevOps / SRE 实战
linux·运维·服务器·ubuntu·运维开发·devops