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


当前回答

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

其他回答

下面是另一种方法,将某些命令的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

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


空的输出

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

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

注意,我使用的是-A而不是-A,因为它省略了当前(.)和父目录(..)的符号项。

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


退出代码

如果要检查命令是否成功执行,可以检查$?,其中包含最后一个命令的退出代码(0表示成功,非0表示失败)。例如:

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

更多信息请点击这里。

if [ -z "$(ls -lA)" ]; then
  echo "no files found"
else
  echo "There are files"
fi

这将运行命令并检查返回的输出(字符串)的长度是否为零。 你可能想要检查“测试”手册页的其他标志。

在要检查的参数周围使用"",否则空结果将导致语法错误,因为没有给出第二个参数(要检查)!

注意:ls -la总是返回。和. .因此,使用这将不工作,请参阅ls手册页。此外,虽然这可能看起来方便和容易,我想它会很容易坏。编写一个根据结果返回0或1的小脚本/应用程序要可靠得多!

有时您希望保存输出(如果它是非空的),以便将其传递给另一个命令。如果是的话,你可以使用

list=`grep -l "MY_DESIRED_STRING" *.log `
if [ $? -eq 0 ]
then
    /bin/rm $list
fi

这样,如果列表为空,rm命令就不会挂起。