2

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.

my script:

#!/bin/bash

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

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

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

Any body able to help me out? Thanks loads.

oguz ismail
  • 1
  • 16
  • 47
  • 69
KYoung
  • 21
  • 3
  • Have a look at [7.1. Introduction to if](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html) in Bash Guide for Beginners. – user3439894 Dec 30 '15 at 19:38

3 Answers3

3

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

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

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

or

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

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

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

Also read: What is the difference between test, [ and [[ ? for a detailed discussion.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

In bash, > is not the operator "greater than". Use -gt instead. Also, your if statment needs to end with fi and not if.

> in bash is used to redirect outputs for programs. E.g. date > date.txt will put the output of the command "date" to a file "date.txt"

To start with bash scripting, you could take a look into this tutorial: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html#toc11

geruetzel
  • 134
  • 6
1

You should use:

if [ 10 -gt $a ]
...

to compare numbers

mauro
  • 5,730
  • 2
  • 26
  • 25