测试命令是否输出空字符串 [英] Test if a command outputs an empty string

查看:27
本文介绍了测试命令是否输出空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试命令是否输出空字符串?

How can I test if a command outputs an empty string?

推荐答案

之前的问题是问如何查看目录下是否有文件.以下代码实现了这一点,但请参阅 rsp 的答案以获得更好的解决方案.

Previously, the question asked how to check whether there are files in a directory. The following code achieves that, but see rsp's answer for a better solution.

命令不返回值——它们输出它们.您可以使用命令替换来捕获此输出;例如$(ls -A).您可以像这样在 Bash 中测试非空字符串:

Commands don’t return values – they output them. You can capture this output by using command substitution; e.g. $(ls -A). You can test for a non-empty string in Bash like this:

if [[ $(ls -A) ]]; then
    echo "there are files"
else
    echo "no files found"
fi

请注意,我使用了 -A 而不是 -a,因为它省略了符号电流 (.) 和父级 (...) 目录项.

Note that I've used -A rather than -a, since it omits the symbolic current (.) and parent (..) directory entries.

注意:正如评论中所指出的,命令替换不捕获尾随换行符.因此,如果命令输出 only 换行符,则替换将不会捕获任何内容并且测试将返回 false.虽然不太可能,但在上面的示例中这是可能的,因为单个换行符是有效的文件名!此答案中的更多信息.

Note: As pointed out in the comments, command substitution doesn't capture trailing newlines. Therefore, if the command outputs only newlines, the substitution will capture nothing and the test will return false. While very unlikely, this is possible in the above example, since a single newline is a valid filename! More information in this answer.

如果你想检查命令是否成功完成,你可以检查$?,它包含最后一个命令的退出代码(成功为零,非零失败).例如:

If you want to check that the command completed successfully, you can inspect $?, which contains the exit code of the last command (zero for success, non-zero for failure). For example:

files=$(ls -A)
if [[ $? != 0 ]]; then
    echo "Command failed."
elif [[ $files ]]; then
    echo "Files found."
else
    echo "No files found."
fi

更多信息这里.

这篇关于测试命令是否输出空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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