【问题标题】:How to invert a condition in Bash [duplicate]如何在 Bash 中反转条件 [重复]
【发布时间】:2018-10-02 09:56:13
【问题描述】:

我想检查 Android 上是否存在目录。

an answer to Check if a file exists with a wildcard in a shell script,我得到了一个想法。所以我使用ADB,如下所示。

if [ adb shell ls ${test_dir}  2> /dev/null ] ;
then
   echo "files exist"
else
   echo "files do not exist"

fi

我是 Bash 脚本的新手。我知道adb shell ls 将返回所有文件名。但是2> /dev/null是什么意思呢?

我只关心files do not exist 条件。那么如何反转条件呢?

第二版

if [ ! adb shell ls ${test_dir}  2> /dev/null ] ;
then
   echo "files exist"
else
   echo "files do not exist"

fi

添加! 对我不起作用。

【问题讨论】:

  • 将所有错误消息发送到/dev/null(比特桶)用if [ ! .... ]反转
  • @DavidC.Rankin 非常感谢。你能回答这个问题吗?
  • 好的,我会写的。
  • 不要在命令周围使用方括号;它们用于测试表达式。见my answer here

标签: bash shell


【解决方案1】:

在表达式中:

if [ adb shell ls ${test_dir}  2> /dev/null ]

重定向2> /dev/nullstderr 上的任何消息重定向(由abd shell ls ${test_dir} 导致的任何错误到/dev/null,被称为bit bucket。本质上,位桶是一个无处可去的系统设备节点。所以您可以将您喜欢的任何输出复制或重定向到/dev/null,然后它就会消失(这意味着它不会被复制到任何地方,也不会被进一步重定向——它只是进入比特桶——一个方便的黑洞) 这具有抑制测试本身的任何输出的效果。

您问题的第二部分询问如何否定(反转)测试子句。简单的答案是将'!' 放在测试的前面。

如果您还有其他问题,请告诉我。


经过进一步讨论和整理adb是一个android工具,解决方案是简单地检查命令本身执行后的返回,例如

$ adb shell ls ${test_dir}  2> /dev/null

然后用

测试返回
if [ "$?" -ne '0' ]; then 
    # handle error
fi

如果您对此问题还有其他问题,请告诉我。

【讨论】:

  • if [ ! adb shell ls ${test_dir} 2> /dev/null ] ?但这对我不起作用。
  • 让我进一步看看您的链接。 abd 不是 bash 命令或测试。如果你正在测试一个空目录,你想要的是:[ -z "$(ls -A "$test_dir")" ] 如果你想知道它是否有文件,那么[ "$(ls -A "$test_dir" | wc -l)" -gt 0 ]
  • 没关系,随着年龄的增长,我的眼睛在交叉:)。您是在测试目录中的文件还是空目录?
  • 我想检查目录是否存在。这是我的错,我会更新我的问题。
  • 如果你想测试一个目录是否存在,那么使用if [ -d "$dirname" ]; then echo "$direname exists"; else echo "$dirname not found"; fi你也可以只检查if [ ! -d "$dirname" ]; then echo "$dirname doesn't exist"; fi
猜你喜欢
  • 2018-05-20
  • 2020-10-23
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 2021-12-29
  • 2013-09-23
相关资源
最近更新 更多