这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
其他回答
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
我更喜欢使用POSIX shell兼容格式执行以下一行代码:
$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"
$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"
对于一些命令,就像我在脚本中所做的那样:
$ [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}
一旦我开始这样做,我就很少再使用完全类型化的语法了!!
有三种不同的方法可以做到这一点:
用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“文件不存在”传真
测试可能也很重要。它对我有用(基于Bash Shell:检查文件是否存在):
test -e FILENAME && echo "File exists" || echo "File doesn't exist"
要反转测试,请使用“!”。这相当于其他语言中的“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!"