Aks
Aks

Reputation: 184

Substituting Bash Variable in a export Command

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.

Upvotes: 1

Views: 465

Answers (2)

Harald Nordgren
Harald Nordgren

Reputation: 12381

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.

Upvotes: 2

l'L'l
l'L'l

Reputation: 47169

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.

Upvotes: 3

Related Questions