使用测试命令在bash中if语句无法按预期工作的比较 [英] Comparison in if statement is not working as expected in bash with test command

查看:50
本文介绍了使用测试命令在bash中if语句无法按预期工作的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一位新手,正在尝试使我的第一个如果那么"陈述生效.我炮制了一个总的bs情况以用作试用,但它不起作用.我已经阅读了关于如何格式化if then的一半doz描述,但是对于我可能做错了什么却一无所知.

I am a rank newbie who is trying to get my very first "if then" statement to work. I concocted a total bs situation to use as a trial but it does not work. I have read about a half doz descriptions about how to format an if then but I get no clue about what I might be doing wrong.

我的剧本:

#!/bin/bash

if [ 10 > $1 ]
    then
    printf "Too big\n"
    else
    printf "Too small\n"
if

我认为我可以在命令行中提供任何数字作为第一个参数,并且脚本会告诉我一个适当的答案.没什么好高兴的我在cmd行上得到的只是:

I figured I could provide any number as the first parameter at the command line and the script would tell me an appropriate answer. No joy. All I ever get at the cmd line is:

Johns-iMac:~ johnyoung$ ./test3 5
Too big
Johns-iMac:~ johnyoung$ ./test3 50
Too big

在实践中,我一直在执行此脚本,最终将其称为"test3"

For the practice I have been doing this script ended up being called "test3"

有人能帮助我吗?谢谢负载.

Any body able to help me out? Thanks loads.

推荐答案

中的> ,如果[10>$ 1] 在测试命令 [中被解释为输出重定向.您可以使用bash内置的 [[[ ]] 进行数值比较.

The > in if [ 10 > $1 ] is interpreted as output redirection in the test command [. You can use bash built-in [[ ]] to to numerical comparison.

#!/bin/bash

if [[ 10 > $1 ]]
    then
    printf "Too big\n"
    else
    printf "Too small\n"
fi

您还可以使用 -gt (大于), -lt (小于), -ge (大于或等于)等数值比较:

You can also use -gt (greater than), -lt(less than), -ge(greater than or equal to) etc numerical comparisons:

if [[ 10 -gt $1 ]] 
...
...
fi

if (( 10 > $1 ))
...
...
fi

通常,在,因为它不会进行全局扩展或单词拆分,并且与测试命令 [.

In general, builtin keyword [[ ]] should be preferred in bash as it doesn't do glob expansion or word splitting and less error prone to use when compared to the test command [.

但是缺点是并非所有的shell都支持 [[[ ]] ,而所有的shell都支持测试命令 [在那里.

But the downside is that [[ ]] is not supported by all shells while the test command [ is supported by all all shells out there.

另请阅读:测试与[和[[?讨论.

这篇关于使用测试命令在bash中if语句无法按预期工作的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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