john
john

Reputation: 11699

How to do string comparison properly in shell script?

I am executing my url through shell script and storing the response in a variable.

http://hostname.domain.com:8080/beat

After hitting the above url, I will be getting the below response which I need to parse it and extract value of state from it

num_retries_allowed: 3 count: 30 count_behind: 100 state: POST_INIT num_rounds: 60 hour_col: 2 day_col: 0

Now I am extracting value of state variable from the above string using grep.

#send the request, put response in variable
DATA=$(wget -O - -q -t 1 http://hostname.domain.com:8080/beat)

#grep $DATA for state
state=$(grep -oP 'state: \K\S+' <<< "$DATA")
[[ -z "$state" ]] && state=0

echo $state

Also if in $DATA variable state: string is not there by any chance, then I want to assign 0 to state variable. After that I want to verify the conditionals and exit out of the script depending on that.

If state is equal to POST_INIT then exit successfully out of the shell script or if state is equal to 0, then exit successfully as well.

if [[ $state -eq "POST_INIT" || $state -eq "0" ]]; then exit 0; fi

So my above if condition is not working somehow. Since what I have noticed is if my state variable value is IN_INIT, then also it is exiting out of the shell script? Is there anything wrong I am doing here in the string comparison?

Upvotes: 3

Views: 227

Answers (2)

Ankita
Ankita

Reputation: 197

trying this

 if [[ "$state" == "POST_INIT" || "$state" == "0" ]]; 

will help because if you use something like [ $state == "POST_INIT" ] , it ignores $state if it is null and would rather read the statement as [ == "POST_INIT". including " " ,prevents that case.

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 80931

-eq is for comparing numbers. = is for comparing strings.

If you were using [ instead of [[ you would be getting an error for a value of POST_INIT and IN_INIT.

$ state=POST_INIT
$ [ $state -eq 0 ]
-bash: [: POST_INIT: integer expression expected
$ echo $?
2

What I believe [[ is doing is actually being more clever and more annoying.

I believe it is expanding the variable and then using the expanded value in an arithmetic context (in which variables are expanded even from bare words) and since the variable POST_INIT doesn't have a value that gets expanded to 0 by default and your check passes.

$ state=POST_INIT
$ [[ $state -eq 0 ]]; echo $?
0
$ POST_INIT=5
$ [[ $state -eq 0 ]]; echo $?
1
$ POST_INIT=0
$ [[ $state -eq 0 ]]; echo $?
0

Upvotes: 2

Related Questions