How to if/else statement in shell script

2019-05-11 18:39发布

问题:

I'm receiveing an error on a simple script when using if/else statement.
The code:

#!/bin/sh
count=100
if [$count > 3]; then
echo "Test IF"
fi

The error: /bin/ash: line 6: [100: not found

回答1:

#!/bin/sh 

count=100;
if [ "$count" -gt 3 ]; then
  echo "Test IF";
fi

Correct your syntax: spaces must be used around [ and ], parameter expansions must be quoted, and -gt is appropriate for numeric comparisons inside of [ ]. > in sh is used as redirection operator; if you want to use it in arithmetical comparison, you must use the bash-only syntax

$(( $count > 3 ))


回答2:

The if statement in shell uses the command [. Since [ is a command (you could also use 'test'), it requires a space before writing the condition to test. To see the list of conditions, type: man test

You'll see in the man page that:

s1 > s2 tests if string s1 is after string s2

n1 gt n2 tests if integer n1 is greater than n2

In your case, using > would work, because string 100 comes after string 3, but it is more logical to write

if [ $count -gt 3 ]; then
   echo "test if"
fi


回答3:

#!/bin/sh 

if [ $var -eq 12 ]; then 
    echo "This is a numeric comparison if example"
fi

if [ "$var" = "12" ]; then
    echo "This is a string if comparison example"
fi

if [[ "$var" = *12* ]]; then
    echo "This is a string regular expression if comparison example"
fi


回答4:

this will also do!

#!/bin/sh
count=100
if [ $count -gt 3 ];
then
    echo "Test IF"
fi


标签: shell