For simplicity and how source/input of this post for the coming scenarios, observe the following
java --version
openjdk 11.0.13 2021-10-19
OpenJDK Runtime Environment Temurin-11.0.13+8 (build 11.0.13+8)
OpenJDK Client VM Temurin-11.0.13+8 (build 11.0.13+8, mixed mode)
Just in case java
command shows the following
-version print product version to the error stream and exit
--version print product version to the output stream and exit
That's why I use the latter for the following commands scenarios:
Therefore with:
#1
java --version | head -n1
openjdk 11.0.13 2021-10-19
#2
x=$(java --version | head -n1)
echo $x
openjdk 11.0.13 2021-10-19
Until here all is ok and expected.
Now taking in consideration the following:
Note I need the approach shown in the previous link to build complex commands according with some options defined by the user through input - assume a command with parameters chosen by the user.
Therefore with:
x="java --version | head -n1"
echo $($x)
OpenJDK Client VM Temurin-11.0.13+8 (build 11.0.13+8, mixed mode) <--- not expected
The output now is different. Why? How to fix it? or what is missing?
I need the same output as Command Substitution without String
Extra Question
- Is valid use command substitution with String as parameter? or is a bad practice?
;
(and subsequent arguments) will be passed as literal parameters to theecho
command"? – Michael Homer Feb 05 '22 at 01:35|
pipe. Is not considered. I did do a research and sadlyeval
is evil – Manuel Jordan Feb 05 '22 at 01:41echo
– Manuel Jordan Feb 05 '22 at 01:54echo $('java' '-version' '|' 'head' '-n1')
, which the accepted answer to the dupe explains. – Kusalananda Feb 05 '22 at 06:34alias x="java --version | head -n1"
works, I am going to do a research if it has some drawbacks aseval
– Manuel Jordan Feb 05 '22 at 13:02