我有一个 bash 脚本:
echo " enter file name "
read $file
if [ -f "$file" ] && [ -s "$file" ]
then
echo " file does not exist, or is empty "
else
echo " file exists and is not empty "
fi
无论我作为 $file
输入什么,它都会给我错误值。我什至可以输入一个根本不存在的文件;它仍然会给我错误的值(value)。这是为什么呢?
最佳答案
检查-s
就足够了,因为它说:
FILE exists and has a size greater than zero
http://unixhelp.ed.ac.uk/CGI/man-cgi?test
你的输出也被切换,所以当文件存在时输出 does not exists
,因为如果文件存在 -s
将给出 TRUE
AND 有一个 size > 0
。
你应该正确地使用:
echo " enter file name "
read file
if [ -s "$file" ]
then
echo " file exists and is not empty "
else
echo " file does not exist, or is empty "
fi
这将为您提供预期的输出。
应该也是
read file
而不是
read $file
如果您想了解更多信息,我建议您阅读 man test
和 man read
https://stackoverflow.com/questions/30080997/