当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

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.
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: