Open ~/.bashrc file.

Create 2 functions to load and unload environment variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
env_load() {
    local env_var=$1
    local path=$2
    if [[ ":${!env_var}:" != *":$path:"* ]]; then
        export $env_var="${!env_var}:$path"
    fi
}

env_unload() {
    local env_var=$1
    local path=$2
    local paths_array=(${!env_var//:/ })
    local new_paths=()
    for item in "${paths_array[@]}"; do
        if [[ "$item" != "$path" ]]; then
            new_paths+=("$item")
        fi
    done
    export $env_var=$(IFS=:; echo "${new_paths[*]}")
}

Now, you can use env_load and env_unload to manage environment variables.

For example, to manage CUDA environment, add these lines to ~/.bashrc:

1
2
3
export CUDA_HOME="/usr/local/cuda-12.1"
alias LOAD_CUDA="env_load PATH $CUDA_HOME/bin; env_load LD_LIBRARY_PATH $CUDA_HOME/lib64"
alias UNLOAD_CUDA="env_unload PATH $CUDA_HOME/bin; env_unload LD_LIBRARY_PATH $CUDA_HOME/lib64"