这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
在为未加引号的变量运行测试时,您应该小心,因为它可能会产生意外的结果:
$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1
建议通常将测试变量用双引号括起来:
#!/bin/sh
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist."
fi
其他回答
有时使用&&和|运算符可能很方便。
类似于(如果您有命令“test”):
test -b $FILE && echo File not there!
or
test -b $FILE || echo File there!
要反转测试,请使用“!”。这相当于其他语言中的“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!"
在为未加引号的变量运行测试时,您应该小心,因为它可能会产生意外的结果:
$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1
建议通常将测试变量用双引号括起来:
#!/bin/sh
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist."
fi
此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
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi