How would i parse a multiline stdout string with a variable in bash script, i am getting error "unary operator expected"
I have a bash script:
#!/bin/bash
JAVA_VERSION="1.6.0_17"
_STDOUT=`java -version`
if [ $JAVA_VERSION = $_STDOUT ]; then
echo "Matched"
else
echo "Not Matched"
fi
i get the result:
java version "1.6.0_17" OpenJDK Runtime Environment (IcedTea6 1.7.5) (rhel-1.16.b17.el5-x86_64) OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode) t4.sh: line 8: [: 1.6.0_17: unary operator expected Not Matched
How would i match $JAVA_VERSION with $_STDOUT when $_开发者_开发技巧STDOUT has multiple lines
You have a few problems.
- It appears
java -version
puts its output on STDERR, not STDOUT, so you'll have to redirect STDERR to STDOUT to parse it. - You need to match the double quotes literally. With
JAVA_VERSION="1.6.0_17"
the shell will remove the quotes, you can wrap the double quotes in single quotes to make them literal. - Finally, if you're going to use
bash
you should be using[[ ]]
and not[ ]
. The latter is actually a synonym to thetest
builtin and the former is native syntax that allows for more capability; one of which is you don't need to quote the variables inside.
.
#!/bin/bash
JAVA_VERSION='"1.6.0_17"'
_STDOUT=$(java -version 2>&1 | awk 'NR==1{print $3}')
if [[ $JAVA_VERSION = $_STDOUT ]]; then
echo "Matched"
else
echo "Not Matched"
fi
Proof of Concept
$ java -version
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Client VM (build 16.3-b01, mixed mode, sharing)
$ JAVA_VERSION='"1.6.0_20"'; _STDOUT=$(java -version 2>&1 | awk 'NR==1{print $3}'); if [[ $JAVA_VERSION = $_STDOUT ]]; then echo "Matched"; else echo "Not Matched"; fi
Matched
$ JAVA_VERSION='"1.6.0_19"'; _STDOUT=$(java -version 2>&1 | awk 'NR==1{print $3}'); if [[ $JAVA_VERSION = $_STDOUT ]]; then echo "Matched"; else echo "Not Matched"; fi
Not Matched
You can use Bash's inbuilt comparison checker to see if a string is contained within another string. So you don't need to pipe into awk
or cut
.
JAVA_VERSION=1.6.0_17
_STDOUT=`java -version 2>&1`
if [[ $_STDOUT == *$JAVA_VERSION* ]]; then
echo "Matched"
else
echo "Not Matched"
fi
Use quotes.
#!/bin/bash
JAVA_VERSION="1.6.0_17"
_STDOUT=`java -version`
if [ "$JAVA_VERSION" = "$_STDOUT" ]; then
echo "Matched"
else
echo "Not Matched"
fi
The problem is not of having multiple lines -- even if the output had appeared in a single line, it wouldn't have matched. You made a good try, but what that code does is like comparing an apple with a basket of fruits. So, we need to isolate the apple from that basket :)
This is how we do it:
Note: Corrected the code as per SiegeX's comments
#!/bin/bash
JAVA_VERSION="1.6.0_17"
_STDOUT=`java -version 2>&1 | grep "java version" | cut -d'"' -f2` # Just extract the version
if [[ "$JAVA_VERSION" = "$_STDOUT" ]]; then
echo "Matched"
else
echo "Not Matched"
fi
精彩评论