开发者

Problem with logical operator in bash script

I read i开发者_JAVA百科n tldp.com that

if [ $condition1 ] && [ $condition2 ]

Same as: if [ $condition1 -a $condition2 ]

Returns true if both condition1 and condition2 hold true..."

but when I tried

if [ $a == 2 ] || [ $b == 4 ]
then
echo "a or b is correct"
else
echo "a and b are not correct"
fi

it gives error. I'm using bash.


Your logic is ok but your comparison operators are incorrect, you should use the '-eq' for comparing integers and '==' for strings. See 'man test' for quick reference, though it's also documented in 'man bash'.

When using integer comparison it is always best to initialise variables to 0 as well otherwise if they remain unset you will get errors.

As mentioned by c00k, use [[ rather than [ if using bash as it is a builtin so bash will not need to shell out to use the /usr/bin/[ command.

i.e.

a=0;b=0
# do something else with a or b
if [[ $a -eq 2 ]] || [[ $b -eq 4 ]]
then
    echo "a or b is correct"
else
    echo "a and b are not correct"
fi


If you're using Bash, then drop the single [ and use double ones [[.
For arithmetic operations, use ((.

So you'd want to write this:

if (( a == 2 )) || (( b == 4 )); then
    echo "foo"
fi # etc


Did you assign a value to a and b? If not you have to (otherwise you definitely should) quote your variables with double quotes:

if [ "$a" == "2" ] || [ "$b" == "4" ]; then
  echo "a or b is correct";
else
  echo "a and b are not correct";
fi


Correct me if I'm wrong. && and || are bash comparison

#!/usr/bin/ksh
set -x    ###### debug mode on 

while :
do
dt=`date '+%M'`

if ([ "$dt" -ge "15"] && [ "$dt" -le "17" ]) || ([ "$dt" -ge "25" ] && [ "$dt" -le "27" ]) 

then

echo "Time-->minutes between 15 to 17 OR 25 to 27"

else

echo "Time--> minutes out of range"
fi

sleep 300 ##### sleep for 5 minutes

done

------------- below lines are debug output

+ + date +%M

dt=17

+ [ 17 -ge 15 ]

+ [ 17 -le 17 ]

+ echo Time--> minutes between 15 to 17 OR 25 to 27

Time--> minutes between 15 to 17 OR 25 to 27

+ date

Sat Mar  3 15:17:23 AST 2012

+ sleep 300

>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

+ :

+ + date +%M

dt=22

+ [ 22 -ge 15 ]

+ [ 22 -le 17 ]

+ [ 22 -ge 25 ]

+ echo Time--> minutes out of range

Time--> minutes out of range

+ sleep 300

^C$    ######## breaking out of loop(terminating the execution).

$ 
$ env |grep -i shell

+ grep -i shell

+ env

SHELL=/bin/ksh

$ set +x   ##### ending debug mode.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜