Click here to Skip to main content
15,889,266 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I am new in shell script. I create one script file and try to run in Windows 10. For this I installed ubuntu. When I run the bash file without function scope, its working. As example

var=$(java -version 2>&1 | awk -F '"' 'NR==1 {print $2}')
echo $var


But if I call them inside a function its not working.

What I have tried:

Bash
#!/bin/bash
myfunc()
{
  echo "$(java -version 2>&1)" | grep "java version" | awk '{ print substr($3, 2, length($3)-2); }'
}



myfunc
Posted
Updated 31-Jul-19 4:15am
Comments
Richard MacCutchan 31-Jul-19 9:42am    
I note that the code in myfunc is different from the code that works. Try running it step by step outside of the function to see which part is failing.

1 solution

The default java installation for ubuntu is openjdk, not the version from Oracle. This means that java -version shows
$ java -version
openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)
OpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)

grep "java version" isn't going to find a match, thus the function returns nothing.

Points to Richard for pointing out that your code is different between mycode and the var = versions.
 
Share this answer
 
Comments
Richard MacCutchan 31-Jul-19 11:17am    
Points to you for a comprehensive explanation. I don't have Java in my WSL Ubuntu, so was not able to test it fully.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900