Home  >  Article  >  Operation and Maintenance  >  How to determine whether a file exists in linux shell

How to determine whether a file exists in linux shell

青灯夜游
青灯夜游Original
2021-11-30 16:01:4238629browse

In the Linux shell, you can use the if statement and the "-e filename" expression to determine whether the file exists. The specific syntax is "if [-e filename]; then echo "file exists"; else echo "file ";fi" does not exist.

How to determine whether a file exists in linux shell

#The operating environment of this tutorial: linux5.9.8 system, Dell G3 computer.

Determine the basic format of the file. [operator file or directory]

How to determine whether a file exists in linux shell

  • -e filename True if filename exists

  • -d filename True if filename is a directory

  • -f filename True if filename is a regular file

  • -L filename True if filename is a symbolic link

  • -r filename True if filename is readable

  • -w filename True if filename is readable Write, true

  • -x filename True if filename is executable

  • -s filename If file length is not 0, It is true

  • -h filename If the file is a soft link, it is true

Common examples

If a file exists, delete it

if [ -f trials ]; then rm ${result_path}trials; fi

If there is no folder, create it

if [ ! -d $result_name ];then
   mkdir -p $result_name
fi

The shell command determines whether the file or folder exists, first look directly at the example:

#!/bin/sh
 
#判断文件存在,判断是否为文件夹等
testPath="/Volumes/MacBookProHD/Mr.Wen/08 shell命令"
testFile="/Volumes/MacBookProHD/Mr.Wen/08 shell命令/fileWen"
 
#判断文件夹是否存在 -d
if [[ ! -d "$testPath" ]]; then
 echo "文件夹不存在"
else
 echo "文件夹存在"
fi
 
#判断文件夹是否存在,并且具有可执行权限
if [[ ! -x "$testFile" ]]; then
 echo "文件不存在并且没有可执行权限"
else
 echo "文件存在并有可执行权限"
fi
 
#判断文件是否存在
if [-e "$testFile"]; then
 echo "文件不存在"
else
 echo "文件存在"
fi

Related recommendations: "Linux Video Tutorial"

The above is the detailed content of How to determine whether a file exists in linux shell. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what is kali linuxNext article:what is kali linux