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

相关推荐
IMPYLH19 分钟前
Linux 的 pinky 命令
linux·运维·服务器·bash
REDcker1 小时前
Linux iptables 与 Netfilter:原理、路径与运维要点
linux·运维·服务器
嵌入式×边缘AI:打怪升级日志3 小时前
Linux 驱动开发入门:从最简单的 hello 驱动到硬件交互
linux·驱动开发·交互
Bert.Cai4 小时前
Linux useradd命令详解
linux·运维
无忧.芙桃5 小时前
进程控制(上)
linux·运维·服务器
十年编程老舅5 小时前
深入 Linux 中断:原理详解 + 实战落地
linux·网络·linux内核·c/c++·中断
Bert.Cai5 小时前
Linux rm命令详解
linux·运维
知识浅谈6 小时前
OpenClaw保姆级安装教程:基于ubuntu系统
linux·ubuntu·node.js
hweiyu006 小时前
Linux命令:suspend
linux·运维·服务器
cyber_两只龙宝7 小时前
【Docker】Docker的资源限制
linux·运维·服务器·docker·云原生·容器