这将检查文件是否存在:
#!/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 "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“文件不存在”传真
其他回答
[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"
此外,该文件可能是一个断开的符号链接,或者是一个非常规文件,例如套接字、设备或fifo。例如,要添加断开符号链接的检查:
if [[ ! -f $FILE ]]; then
if [[ -L $FILE ]]; then
printf '%s is a broken symlink!\n' "$FILE"
else
printf '%s does not exist!\n' "$FILE"
fi
fi
此代码也有效。
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File '$FILE' Exists"
else
echo "The 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
您还可以在一行中对多个命令进行分组
[-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"