mher.nader
mher.nader

Reputation: 28

Shell variables are not created with export in script

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.

Upvotes: 1

Views: 108

Answers (2)

FMa
FMa

Reputation: 88

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"

Upvotes: 1

deepakchethan
deepakchethan

Reputation: 5600

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.

Upvotes: 2

Related Questions