如何在远程主机解析java -version版本号并赋值给变量
Retrieve Remote Java Version and Store in a Variable (Single Command)
Got it, let's break this down into a clean, single command that does exactly what you need: run java -version on a remote Linux host, parse the version number, and save it to a local variable.
The One-Liner
REMOTE_JAVA_VERSION=$(ssh your-username@remote-host 'java -version 2>&1 | grep -E "version" | sed -E "s/.*version \"([0-9]+\.[0-9]+\.[0-9]+).*/\1/"')
Let's Break Down Each Part
ssh your-username@remote-host '...': Establishes an SSH connection to your remote host and runs the command inside the single quotes on that machine.java -version 2>&1: By default,java -versionoutputs to stderr (standard error) instead of stdout. The2>&1redirects stderr to stdout, so our next commands can capture the output properly.grep -E "version": Filters the output to only the line containing the version string—this works for both OpenJDK and Oracle JDK, which have slightly different but compatible output formats.sed -E "s/.*version \"([0-9]+\.[0-9]+\.[0-9]+).*/\1/": Uses a regular expression to extract the core version number (e.g., pulls11.0.18fromopenjdk version "11.0.18" 2023-01-17).
Want the Full Version String?
If you need the complete version string including update numbers or distribution-specific suffixes (like 1.8.0_361 or 11.0.18+10-post-Ubuntu-0ubuntu122.04), adjust the sed part to capture everything inside the quotes:
REMOTE_JAVA_VERSION=$(ssh your-username@remote-host 'java -version 2>&1 | grep -E "version" | sed -E "s/.*version \"([^\"]+)\".*/\1/"')
Important Notes
- SSH Access: Make sure your local machine can connect to the remote host via SSH. For non-interactive use (so the command runs without prompting for a password), set up SSH key-based authentication.
- Java Path: If Java isn't in the remote user's default
PATH, specify the full path to the Java executable (e.g.,/usr/lib/jvm/java-11-openjdk-amd64/bin/java -version). - Output Variations: Some older Java versions might have slightly different output formats, but the above commands should work for most modern OpenJDK and Oracle JDK releases.
内容的提问来源于stack exchange,提问作者jdoe08
相关产品推荐
相关产品推荐

