简体   繁体   中英

Bash parameter shell expansion counting unknown character

I'm trying to compare the values of two strings; "$mongoOne" and "true"

mongoOne=$(docker exec -it mongo-1 mongo --quiet --eval "d=db.isMaster(); print( d['ismaster'] )" )

This is a simple docker command that returns true/false depending on whether or not a node is master.

If I echo $mongoOne, i see the response:

true

However, when I run:

if [ "$mongoOne" = "true" ]
then 
  echo "master"
else
  echo "secondary"
fi

The code responds with secondary instead of master.

I've found that when using parameter shell expansion to count the characters in $mongoOne, I see the following:

echo ${#mongoOne}
5

mongoOne contains 5 characters, not the expected 4.

I've tried piping this into a file, and I see no trailing whitespace or new lines.

Can anyone advise on what this 5th character could be?

Thanks for the responses all. After some more digging, I found a Git issue for this exact problem: https://github.com/moby/moby/issues/8513

The fix was removing -it and replacing it with --tty=false.

mongoOne=$(docker exec --tty=false mongo-1 mongo --quiet --eval "d=db.isMaster(); print( d['ismaster'] )" )
if [ $(grep -o "$mongoOne") = "true" ]
then 
  echo "master"
else
  echo "secondary"
fi

You might have better luck with this. The -o command to grep, only matches the exact text that you want.

I'm also not completely clear on how "if" compares strings, to be honest. If I needed to do something like this, I'd probably want the MongoOne variable to contain "1" rather than "true," because I know that numerical comparison works directly, via subtraction. Text is for users; computers need numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM