这将检查文件是否存在:
#!/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"
其他回答
如果要使用test而不是[],则可以使用!要获得否定:
if ! test "$FILE"; then
echo "does not exist"
fi
测试可能也很重要。它对我有用(基于Bash Shell:检查文件是否存在):
test -e FILENAME && echo "File exists" || echo "File doesn't exist"
envfile=.env
if [ ! -f "$envfile" ]
then
echo "$envfile does not exist"
exit 1
fi
最简单的方法
FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"
在为未加引号的变量运行测试时,您应该小心,因为它可能会产生意外的结果:
$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1
建议通常将测试变量用双引号括起来:
#!/bin/sh
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist."
fi