如何测试命令是否输出空字符串?
当前回答
正如Jon Lin所评论的,ls -al将始终输出(for。和. .)。您希望ls -Al避免这两个目录。
例如,你可以把命令的输出放到一个shell变量中:
v=$(ls -Al)
较旧的、非嵌套的符号是
v=`ls -Al`
但我更喜欢嵌套符号$(…)
您可以测试该变量是否为非空
if [ -n "$v" ]; then
echo there are files
else
echo no files
fi
你可以把两者结合起来,就像[-n "$(ls -Al)"];然后
有时,ls可能是某个shell别名。您可能更喜欢使用$(/bin/ls -Al)。参见ls(1)和hier(7)和environ(7)和你的~/。bashrc(如果你的shell是GNU bash;我的交互式shell是zsh,定义在/etc/passwd -见passwd(5)和chsh(1))。
其他回答
有时您希望保存输出(如果它是非空的),以便将其传递给另一个命令。如果是的话,你可以使用
list=`grep -l "MY_DESIRED_STRING" *.log `
if [ $? -eq 0 ]
then
/bin/rm $list
fi
这样,如果列表为空,rm命令就不会挂起。
if [ -z "$(ls -lA)" ]; then
echo "no files found"
else
echo "There are files"
fi
这将运行命令并检查返回的输出(字符串)的长度是否为零。 你可能想要检查“测试”手册页的其他标志。
在要检查的参数周围使用"",否则空结果将导致语法错误,因为没有给出第二个参数(要检查)!
注意:ls -la总是返回。和. .因此,使用这将不工作,请参阅ls手册页。此外,虽然这可能看起来方便和容易,我想它会很容易坏。编写一个根据结果返回0或1的小脚本/应用程序要可靠得多!
下面是另一种方法,将某些命令的std-out和std-err写入临时文件,然后检查该文件是否为空。这种方法的一个好处是它捕获两个输出,并且不使用子外壳或管道。后面这些方面很重要,因为它们会干扰捕获bash退出处理(例如这里)
tmpfile=$(mktemp)
some-command &> "$tmpfile"
if [[ $? != 0 ]]; then
echo "Command failed"
elif [[ -s "$tmpfile" ]]; then
echo "Command generated output"
else
echo "Command has no output"
fi
rm -f "$tmpfile"
我猜你想要ls -al命令的输出,所以在bash中,你会有这样的东西:
LS=`ls -la`
if [ -n "$LS" ]; then
echo "there are files"
else
echo "no files found"
fi
Bash参考手册
6.4 Bash条件表达式
-z string
True if the length of string is zero.
-n string
string
True if the length of string is non-zero.
你可以使用速记版:
if [[ $(ls -A) ]]; then
echo "there are files"
else
echo "no files found"
fi