bash “如果 [假];"返回真而不是假——为什么? [英] bash "if [ false ];" returns true instead of false -- why?

查看:21
本文介绍了bash “如果 [假];"返回真而不是假——为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的输出是True?

#!/bin/sh

if [ false ]; then
    echo "True"
else
    echo "False"
fi

这将始终输出 True,即使条件似乎另有说明.如果我删除括号 [] 那么它可以工作,但我不明白为什么.

This will always output True even though the condition would seem to indicate otherwise. If I remove the brackets [] then it works, but I do not understand why.

推荐答案

您正在运行带有参数false"的 [(又名 test)命令,而不是运行命令 false.因为false"是一个非空字符串,所以 test 命令总是成功的.要实际运行该命令,请删除 [ 命令.

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

这篇关于bash “如果 [假];"返回真而不是假——为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆