这将检查文件是否存在:

#!/bin/bash

FILE=$1     
if [ -f $FILE ]; then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi

如何仅检查文件是否不存在?


当前回答

您可以这样做:

[[ ! -f "$FILE" ]] && echo "File doesn't exist"

or

if [[ ! -f "$FILE" ]]; then
    echo "File doesn't exist"
fi

如果要同时检查文件和文件夹,请使用-e选项而不是-f-对于常规文件、目录、套接字、字符特殊文件、块特殊文件等,e返回true。

其他回答

使用!:否定测试中的表达式([是其别名)

#!/bin/bash
FILE=$1

if [ ! -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

相关的手册页是man-test,或者,对于内置的bash命令,相当于man[-或help-test或help]。

或者(不常用)您可以使用以下方法否定测试结果:

if ! [ -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

该语法在“管道”和“复合命令”部分的“man 1 bash”中进行了描述。

要反转测试,请使用“!”。这相当于其他语言中的“not”逻辑运算符。试试看:

if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

或以稍微不同的方式书写:

if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

或者您可以使用:

if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

或者,将所有内容放在一起:

if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

可以写成(使用“and”运算符:&&):

[ ! -f /tmp/foo.txt ] && echo "File not found!"

看起来像这样更短:

[ -f /tmp/foo.txt ] || echo "File not found!"

有三种不同的方法可以做到这一点:

用bash否定退出状态(没有其他答案这么说):如果[-e“$file”];然后echo“文件不存在”传真或:! [-e“$file”]&&echo“文件不存在”在测试命令中否定测试[(这是之前大多数答案给出的方式):如果[!-e“$file”];然后echo“文件不存在”传真或:[!-e“$file”]&&echo“文件不存在”在测试结果为阴性时采取行动(||而不是&&):仅限:[-e“$file”]||echo“文件不存在”这看起来很愚蠢(IMO),除非您的代码必须可移植到缺少管道否定运算符(!)的Bourne shell(如Solaris 10或更早版本的/bin/sh),否则不要使用它:如果[-e“$file”];然后:其他的echo“文件不存在”传真

此shell脚本还可用于查找目录中的文件:

echo "enter file"

read -r a

if [ -s /home/trainee02/"$a" ]
then
    echo "yes. file is there."
else
    echo "sorry. file is not there."
fi

要测试文件是否存在,参数可以是以下任一项:

-e: Returns true if file exists (regular file, directory, or symlink)
-f: Returns true if file exists and is a regular file
-d: Returns true if file exists and is a directory
-h: Returns true if file exists and is a symlink

以下所有测试都适用于常规文件、目录和符号链接:

-r: Returns true if file exists and is readable
-w: Returns true if file exists and is writable
-x: Returns true if file exists and is executable
-s: Returns true if file exists and has a size > 0

示例脚本:

#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exist"
fi