这将检查文件是否存在:

#!/bin/bash

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

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


当前回答

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

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

其他回答

我更喜欢使用POSIX shell兼容格式执行以下一行代码:

$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"

$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"

对于一些命令,就像我在脚本中所做的那样:

$  [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}

一旦我开始这样做,我就很少再使用完全类型化的语法了!!

测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):

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

if [ ! -f "$envfile" ]
then
    echo "$envfile does not exist"
    exit 1
fi

您还可以在一行中对多个命令进行分组

[-f“文件名”]||(echo test1&&echo test2&&echo test3)

or

[-f“文件名”]| |{echo test1&&echo test2&&echo test3;}

如果文件名不退出,输出将为

test1
test2
test3

注意:(…)在子shell中运行,{…;}在同一个shell中运行。

测试可能也很重要。它对我有用(基于Bash Shell:检查文件是否存在):

test -e FILENAME && echo "File exists" || echo "File doesn't exist"