如何检查文件存在

如何使用shell脚本确定文件是否存在?

即:

#!/bin/sh if [ Does File Exist? ] then do this thing fi 

除非需要使用/ bin / sh,否则可能需要/ bin / bash,/ bin / sh更受限制。 所以,如果你使用bash:

像这样:

  if [[ -e filename ]]; then echo 'exists' fi 

如果你的文件名在一个variables中,那么使用下面的内容,如果文件中有一个空格,双引号是很重要的:

 if [[ -e "$myFile" ]]; then echo 'exists' fi 

如果您使用的是sh,并且希望与IEEE Std 1003.1,2004版本兼容,请改为使用单个括号。 -e开关仍然受支持。

if [ -f filename ]

将testing一个正规文件的存在。 还有其他的开关,你可以通过它来检查文件的可执行文件或其他属性。

文件testing的参考页面

一旦你浏览了所有这些页面,
方便地保存此参考表 。

总是有man页面:

man test

只要注意,如果你想要所有sh shell(不仅是bash)和跨平台的东西,唯一的方法是:

 ls filename >/dev/null 2>&1 if [ $? = 0 ]; then echo "File exists" fi