bash 的奇怪之处不是运算符
我正在尝试确定文件或目录是否不存在。我尝试了以下命令来查看文件是否存在并且它们正常工作:
if [ -a 'settings.py' ]; then echo 'exists'; fi
exists #output
if [ -a 'foo' ]; then echo 'exists'; fi #outputs nothing
但是当我尝试这样做时:
if [ ! -a 'settings.py' ]; then echo 'does not exist'; fi
does not exist #shouldn't be output since the file does exist
if [ ! -a 'foo' ]; then echo 'does not exist'; fi
does not exist
无论如何都会输出“不存在”。
I'm trying to determine if a file or directory doesn't exist. I tried the following commands to see if a file does exist and they work correctly:
if [ -a 'settings.py' ]; then echo 'exists'; fi
exists #output
if [ -a 'foo' ]; then echo 'exists'; fi #outputs nothing
But when I try this:
if [ ! -a 'settings.py' ]; then echo 'does not exist'; fi
does not exist #shouldn't be output since the file does exist
if [ ! -a 'foo' ]; then echo 'does not exist'; fi
does not exist
'does not exist' is output no matter what.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我之前在使用
[
命令时遇到过问题。我更喜欢[[
变体,因为它更强大,而且根据我的经验,不太容易出现这样的“陷阱”。如果您使用
[[
命令,您的测试命令可以正常工作:I've had problems with the
[
command before. I prefer the[[
variant since it's much more powerful and, in my experience, less prone to "gotchas" like this.If you use the
[[
command, your test commands work fine:尝试使用
-e
代替-a
此页面位于 Linux 文档项目 说:
-a
与-e
效果相同。但它已被弃用,并且不鼓励使用。Try using
-e
in place of-a
This page on the Linux Documentation Project says:
-a
is identical in effect to-e
. But it has been deprecated, and its use is discouraged.您可以使用
测试
you can use
test