为什么“如果[[[-z“ ls -l / non_existing_file 2> / dev / null”]不正确

问题描述

我想通过检查/ dev / disk / by-uuid / 1234-5678来检查是否仍然插入了外部驱动器。

但是,我知道使用以下方法可以轻松得多:

if ! [ -e "/non_existing_file" ]
   echo "File dont exists anymore"
fi

但是我仍然想知道标题中的脚本为什么不起作用。是因为ls的退出代码吗?

谢谢。

解决方法

看起来ls -l /nonexisting是一个未执行的字符串。如果它在子shell中执行,则应该可以正常工作。

比较标题中的示例:

if [[ -z "ls -l something.txt 2> /dev/null" ]]; then 
  echo "file does not exist"
fi

...,该版本可按预期返回:

if [[ -z "$(ls -l something.txt 2> /dev/null)" ]]; then
  echo "file does not exist"
fi