LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   In BASH shell, how do I export a variable from a script. (https://www.linuxquestions.org/questions/linux-software-2/in-bash-shell-how-do-i-export-a-variable-from-a-script-816123/)

MichaelG67 06-24-2010 09:37 AM

In BASH shell, how do I export a variable from a script.
 
Hello.

I have read several threads on this already, but none of the solutions work for me or apply to my situation.

I need to be able to set a variable that is used by my build environment. I need to be able to change this variable "on the fly" as I work with multiple build environments. A portion of the variable is arbitrary, so I need to treat the arbitrary portion of the variable as an argument.

I would normally just create an alias, but BASH doesn't support arguments to aliases. So the workaround for the no-alias-arguments bug is to use a script. No problem. Except the variable I set in the script does not exist when I exit the script.

Now, if I run the script by using "$ . myscript" it works in that the variable is set after it exits. The problem is the argument checking I have in the script doesn't work anymore.

BASH aliases don't support arguments and I can't export a variable from a script unless I source the script (is it even a script at that point?) Maybe I am simply taking the wrong approach. So I am open to other approaches to solving the original problem (should of changing my build environment of course).

Thanks

David the H. 06-24-2010 10:31 AM

There is no way to directly set a variable in a shell from a script. Commands can only affect the current shell or subshells below it. Your only options are to set it in the shell itself or source it from a file.

And no, you can't arguments in aliases, but you can use them in shell functions. So one thing you can do is create a function like this, place it in your bashrc or other sourced file, and you'll have the ability to set the variable on the fly.

Code:

function setvar {
        export MYVAR="$1"
}

Edit: by the way, I personally use a similar function to "turn on" and off a set of scripts that I have by modifying the PATH variable on the fly. It works like a charm.

Code:

myscripts ()
{
    pathadd="$HOME/my_scripts";
    case $1 in
        on)
            [[ $PATH =~ $pathadd ]] || export PATH="${PATH}:$pathadd"
        ;;
        off)
            export PATH="${PATH//:$pathadd/}"
        ;;
    esac
}


MichaelG67 06-24-2010 01:03 PM

That was it. I had the wrong approach. A function was the way to go. Thank you David_the_H.


All times are GMT -5. The time now is 01:29 PM.