这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
最简单的方法
FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"
其他回答
[[ -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 does not exist"
fi
相关的手册页是man-test,或者,对于内置的bash命令,相当于man[-或help-test或help]。
或者(不常用)您可以使用以下方法否定测试结果:
if ! [ -f "$FILE" ]
then
echo "File $FILE does not exist"
fi
该语法在“管道”和“复合命令”部分的“man 1 bash”中进行了描述。
此shell脚本还可用于查找目录中的文件:
echo "enter file"
read -r a
if [ -s /home/trainee02/"$a" ]
then
echo "yes. file is there."
else
echo "sorry. file is not there."
fi
要测试文件是否存在,参数可以是以下任一项:
-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
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi