这将检查文件是否存在:

#!/bin/bash

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

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


当前回答

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

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

or

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

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

test1
test2
test3

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

其他回答

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

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

to

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

or

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

最简单的方法

FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"
envfile=.env

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

有时使用&&和|运算符可能很方便。

类似于(如果您有命令“test”):

test -b $FILE && echo File not there!

or

test -b $FILE || echo File there!

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

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