这将检查文件是否存在:

#!/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中运行。

其他回答

要反转测试,请使用“!”。这相当于其他语言中的“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 Shell:检查文件是否存在):

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

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

-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

Bash文件测试

-b filename-阻止特殊文件-c filename-特殊字符文件-d directoryname-检查目录是否存在-e filename-检查文件是否存在,无论其类型(节点、目录、套接字等)-f filename-检查常规文件是否存在,而不是目录-G文件名-检查文件是否存在并且由有效组ID拥有-G文件名set group id-如果文件存在并且是set group id,则为True-k文件名-粘滞位-L文件名-符号链接-O filename-如果文件存在并且由有效用户id拥有,则为True-r filename-检查文件是否可读-S filename-检查文件是否为套接字-s filename-检查文件大小是否为非零-u filename-检查是否设置了文件集用户id位-w filename-检查文件是否可写-x filename-检查文件是否可执行

如何使用:

#!/bin/bash
file=./file
if [ -e "$file" ]; then
    echo "File exists"
else 
    echo "File does not exist"
fi 

可以使用!操作人员

#!/bin/bash
file=./file
if [ ! -e "$file" ]; then
    echo "File does not exist"
else 
    echo "File exists"
fi 

最简单的方法

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