Search code examples
bashmacossh

Mac Environment Variable Not Detected If Using .sh File


Mac Environment Variable works on Terminal but Not Detected If Using .sh File

I have script to build Unity libraries which using .sh and the script need Android sdk, so I add Adroid sdk path to environment variable. In terminal, echo $ANDROID_HOME return the correct path, but if I echo from .sh file it returns nothing.

I have tried add the environment variable in .bash_profile or .zshrc or .zprofile . And everytime after add patch I run the source command like source ~/.bash_profile. And everytime I try echo $ANDROID_HOME it works but just in terminal. Using .sh file it returns nothing.

I also tried using sudo when will add the environment but no luck.

Beisdes echo $ANDROID_HOME (which return nothing/black) I also try to check the environment like this in .sh file and it goes into error echo

#!/bin/sh

# shellcheck disable=SC2039

. $(dirname $0)/common.sh

source "$PROJECT_ROOT/scripts/build.properties"

info "Starting build"
# Check for required settings
if [ -z "$ANDROID_HOME" ]; then
    echo "${RED}ERROR: ANDROID_HOME environment variable not set${NC}"
    echo "${RED}Please set the ANDROID_HOME environment variable to point to your android sdk${NC}"
    exit 1
fi

Btw, I run .sh from terminal in the script folder with ./script.sh or sh ./script.sh

I don't know if it help, but here is my environment variable in .bash_profile or .zshrc or .zprofile

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

# Setting PATH for Python 3.8
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"
export PATH
eval "$(/opt/homebrew/bin/brew shellenv)"
export
ANDROID_HOME=/Applications/Unity/Hub/Editor/2021.1.17f1/PlaybackEngines/AndroidPlayer/SDK
export PATH=$PATH:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/emulator
export
JAVA_HOME=/Applications/Unity/Hub/Editor/2021.1.17f1/PlaybackEngines/AndroidPlayer/OpenJDK
export PATH=$PATH:$JAVA_HOME/bin
export ANDROID_NDK_HOME=/Applications/Unity/Hub/Editor/2021.1.17f1/PlaybackEngines/AndroidPlayer/NDK

I'm using Mac Studio Apple M1 Max , MacOS 13.1 (22C65),


Solution

  • At the beginning of the script add line:

    source ~/.zshrc