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

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

问题描述

我怎么能测试一个命令输出空字符串?

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

推荐答案

命令不的收益的价值观 - 他们将其输出。您可以通过使用一个子shell捕获该输出;例如 $(LS -A)。您可以测试在猛砸一个非空字符串是这样的:

Commands don’t return values – they output them. You can capture this output by using a subshell; 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.

如果您要检查该命令成功完成,您可以检查 $?,其中包含的最后一个命令的退出code(零成功,失败非零)。例如:

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天全站免登陆