1

I am trying to set my Java version by passing the version to a function. However, I am not sure how I can substitute the bash argument in the command. Below is the function I am using

function setTheJavaVersion(){
   export JAVA_HOME=`/usr/libexec/java_home -v '$1*'`
}

I am calling the function as -

setTheJavaVersion 1.7

The 1.7 is stored in "$1" but as expected I get the error message -

Unable to find any JVMs matching version "$1*".

Not a bash expert so excuse me if its a silly question.

2 Answers 2

3

You have a few things that are incorrect.

function setTheJavaVersion() {
   ver=$(/usr/libexec/java_home -v "$1")
   export JAVA_HOME=$ver
}
  1. Declare and assign your export separately to avoid masking return values.
  2. For shell expansion instead of using legacy backticks use the $( ... ) syntax instead.
  3. With your argument $1 you'll need double quotes around it since it won't work with shell expansion and single quotes; the * on the end of it is pointless.
Sign up to request clarification or add additional context in comments.

Comments

2

The quoting is the problem here. Change

'$1*'

to

"$1"'*'

to allow the first argument to be expanded. Single quotes and double quotes are different in shell script. Double quotes (") allow variables to be expanded within the expression, whereas single quotes give you literally $1.

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.