这将检查文件是否存在:

#!/bin/bash

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

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


当前回答

此代码也有效。

#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
 echo "File '$FILE' Exists"
else
 echo "The File '$FILE' Does Not Exist"
fi

其他回答

在为未加引号的变量运行测试时,您应该小心,因为它可能会产生意外的结果:

$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1

建议通常将测试变量用双引号括起来:

#!/bin/sh
FILE=$1

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

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

用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“文件不存在”传真

此代码也有效。

#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
 echo "File '$FILE' Exists"
else
 echo "The File '$FILE' Does Not Exist"
fi

如果要使用test而不是[],则可以使用!要获得否定:

if ! test "$FILE"; then
  echo "does not exist"
fi

值得一提的是,如果需要执行单个命令,可以缩写

if [ ! -f "$file" ]; then
    echo "$file"
fi

to

test -f "$file" || echo "$file"

or

[ -f "$file" ] || echo "$file"