1

I am writing a simple script that export variables based on condition. But after running the script none of the variables are accessible. The code is as follows:

#!/bin/bash
if [[ $1 == 11 ]]; then
    echo "Loading java 11"
    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk-11.0.11.jdk/Contents/Home"
else
    echo "Loading java 8"
    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"
fi

I am running with ./file.sh 11 and bash file.sh 11 but both echo Loading 11 but does not load.

2
  • No, sorry I added old script with bugs. I have added correct code now. Thanks Commented Jun 30, 2021 at 7:50
  • @mher.nader: What does does not load.? I don't get the point of your script: You set a variable, but you aren't usign it anywhere. Please be more precises in your description in describe exactly what you did, what effect you hoped to see, and what effect you saw instead. Commented Jun 30, 2021 at 9:16

2 Answers 2

2

You need to use source the file with source file.sh 11 or . file.sh 11 instead. Then the shell commands in script will be executed in the current shell as if typed from the command line. Else with bash a new session is created and your commands are run within that. So variables are not accessible in your session.

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

Comments

1

Also, you need to

export $JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"

to

Removing the $ sign

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"

1 Comment

Yes, sorry I had updated wrong code. Thank you for the answer.

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.