简体   繁体   中英

How can I parse java's version number from "java -version" and assign it to a variable on a remote host?

I want to fetch the Java version in Linux in a single command then save the output to a variable.

Using the command below assigns the variable to the local version of java. I want to run java -version on the remote host, parse the version number then save the output to a variable.

ssh -q -t $server "OLDJAVA=`java -version 2>&1 | cut -s -d '"' -f2`"

You need to run the command on the remote host and set a local variable to the output, which ssh will forward:

OLDJAVA=$(ssh -q $server "java -version 2>&1 | cut -s -d '\"' -f2")

The '\\"' responds to the need to send an escaped quote to the remote server. (I missed this on the first iteration.) However, it is easier to do the redirection and post-processing on the local machine, since ssh will pass both stdout and stderr back. This results in the somewhat simpler

OLDJAVA=$(ssh -q $server java -version 2>&1 | cut -s -d \" -f2)

In both cases, I removed the -t option because it doesn't seem to be needed. It's possible that the -q option will create more problems than it solves (since you will definitely want to react to an ssh error.)

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