Bash的检查显示文件中存在与不存在的文件? [英] Bash check shows file exists for non-existent files?

查看:300
本文介绍了Bash的检查显示文件中存在与不存在的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行在bash以下内容:

Run the following in bash:

   stuff=`rpm -ql <some package> | grep dasdasdfd`

(不存在的文件包中,退出code = 1,标准输出为空)

(non existent file in package, exit code = 1, stdout is empty)

  if [ -f $stuff ]; then echo "whaaat"; fi

上面的命令检查,如果文件存在......但是:

Above command checks if file exists... but:

file $stuff

只是打印使用信息文件...以及

Just prints usage info for file... and

stat $stuff

缺少操作数...

Missing operand...

能否有人请解释一下为什么?这是一个错误?难道我做错了什么?我只是想确保这是一个包中的文件是FS present

Can someone please explain why? Is this a bug? Am I doing something wrong? I just want to make sure that a file that's in the package is present on fs

推荐答案

您可能需要围绕 $的东西在报价

if [ -f "$stuff" ]; then

作为一般规则,你几乎的总是的希望周围添加引号路径名无处不在,你使用它们。

As a general rule, you almost always want to add quotes around pathnames everywhere you use them.

我觉得更有益的思考或shell脚本为宏,这是在第一次使用自己的价值扩展的变量。这是从不同的变量在几乎所有其他的编程语言。

I find it more useful to think or variables in shell scripting as "macros", which are expanded on first use to their value. This is different from variables in almost every other programming language.

所以,如果 $的东西包含的Hello World (注意空格),这将是一样的,如果你'已经键入:

So if $stuff contains hello world (notice the space), it would be the same as if you've typed:

[ -f hello world ]

这显然是一个错误。

which is obviously an error.

在这种情况下,你提到你正在处理一个不存在的文件,所以 $的东西居然是空的,它会像打字:

In this case, you mentioned that you're dealing with a non-existent file, so $stuff is actually empty, which would be like typing:

[ -f ]

这实际上是有效的,但总是成功。这是一个有点晦涩测试行为,从的 POSIX规范我们读到测试总是成功的,如果有如果只有一个参数(在这种情况下,参数是 -f

Which is actually valid, but always succeeds. This is a bit of obscure test behaviour, from the POSIX spec we read that test always succeeds if there if only a single argument (in this case, the argument is -f):

1的说法:结果
  退出真(0)如果$ 1是不是null;否则,退出错误的。

1 argument:
Exit true (0) if $1 is not null; otherwise, exit false.

这可能是方便的书写:

[ $variable_that_may_or_may_not_be_defined ]

如果您添加引号,你传递2个参数,更加理智的事情发生了:

If you add quotes, you're passing 2 arguments, and more sane things happen:

if [ -f "" ]; then

这篇关于Bash的检查显示文件中存在与不存在的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆