如何检查文件是否存在

Sim*_*son 3 linux unix-shell

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

IE:

#!/bin/sh

if [ Does File Exist? ]
then
    do this thing
fi
Run Code Online (Sandbox Code Playgroud)

Kyl*_*ndt 9

除非您需要使用 /bin/sh,否则您可能需要 /bin/bash,而 /bin/sh 受到更多限制。因此,如果您使用 bash:

像这样:

 if [[ -e filename ]]; then
    echo 'exists'
 fi
Run Code Online (Sandbox Code Playgroud)

如果您的文件名在变量中,请使用以下内容,如果文件中有空格,则双引号很重要:

if [[ -e "$myFile" ]]; then
   echo 'exists'
fi
Run Code Online (Sandbox Code Playgroud)

如果您正在使用 sh,并希望与 IEEE Std 1003.1,2004 版兼容,请改用单括号。-e 开关仍受支持。