1

I'm new to Bash and trying to store eval command output in a variable. This is my code to check Java version:

javaPath="/opt/Java/i386/jre1.8.0_181/bin/Java -version"
output=eval $javaPath
echo "Java version is: $output"

Output:

java version "1.8.0_181"
Java(TM) SE Runtime Environment (build ...)
Java HotSpot(TM) 64-Bit Server ...
Java version is:

Question: how can I store command output in $output?

1 Answer 1

4

You don't need to use eval here. Don't use it unless you clearly know what you are trying to do with it. See Eval command and security issues

For your use case, though a simple function would suffice. Also I see the java -version gets printed to standard error stream stderr(2) instead of stdout(1).

javaVersion() {
    /opt/Java/i386/jre1.8.0_181/bin/Java -version 2>&1 >/dev/null
}

and put the result in a variable using command substitution, $(..) which runs your command puts the result in a variable

ouput="$(javaVersion)"
printf '%s\n' "$output"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.