1

I am writing a shell script which is using a environment variable.

The environment variable has $1 set in the value. When I am using the env variable in the script, I need to use the $1 as the parameter passed from the script arguments.

Example:

export EXPORT_VAR="-DmyVariable=\$1"

In a shell script (myScript.sh), I have used the above env variable like below.

#!/bin/bash

exec $JAVA_HOME/bin/java $EXPORT_VAR com.myProject.myJob "$@"

I am running the script as follows:

./myScript.sh var1 var2

I want the following command to be executed

exec $JAVA_HOME/bin/java -DmyVariable=var1 com.myProject.myJob "var1 var2"

Please advise.


$1 is just an example. The environment variable can have $2....$N. The same variable should be assigned to -DmyVariable while execution

2 Answers 2

2

I would suggest refactoring your script so you can pass in the variable as an option.

#!/bin/bash
case $1 in
 -e | --export-variable )
   myvar=$2
   shift 2 ;;
esac
exec $JAVA_HOME/bin/java -DmyVariable="$myvar" com.myProject.myJob "$myvar" "$@"

You might want to change the script so it requires the -e option or specifies a reasonable default value. This is just to give you an idea of how to refactor the problem.

Sign up to request clarification or add additional context in comments.

Comments

0

You can write your script as :

#!/bin/bash

exec $JAVA_HOME/bin/java -DmyVariable=$1 com.myProject.myJob "$1 $2"

1 Comment

The $1 variable is not fixed. There are many case where it might be $2 or $3.

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.