这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
envfile=.env
if [ ! -f "$envfile" ]
then
echo "$envfile does not exist"
exit 1
fi
其他回答
测试可能也很重要。它对我有用(基于Bash Shell:检查文件是否存在):
test -e FILENAME && echo "File exists" || echo "File doesn't exist"
值得一提的是,如果需要执行单个命令,可以缩写
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"
要测试文件是否存在,参数可以是以下任一项:
-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
envfile=.env
if [ ! -f "$envfile" ]
then
echo "$envfile does not exist"
exit 1
fi