测试如果命令输出为空字符串

编程入门 行业动态 更新时间:2024-10-26 20:26:42
本文介绍了测试如果命令输出为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多信息这里。

更多推荐

测试如果命令输出为空字符串

本文发布于:2023-10-08 13:54:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472826.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   为空   命令   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!