[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Is there a way to make variables used in a sourced scrip
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] Is there a way to make variables used in a sourced script local to the script being sourced, so that the variables will not be available in the script where the "source" command is called? |
Date: |
Sun, 7 Jun 2015 21:44:20 -0500 |
On Sun, Jun 7, 2015 at 9:11 PM, Peng Yu <address@hidden> wrote:
> Is there a way to make variables used in a sourced script local to the script
> being sourced, so that the variables will not be available in the script
> where the "source" command is called?
Don't put code outside of functions in sourced scripts. Put all library code
into functions, source the file, then call the functions.
You may pass positional parameters to a sourced script as well as export
variables to the environment of the source command, but if you just keep
everything confined to functions then neither of those are useful. Example of
both:
$ bash 3<<\EOFB <<\EOFA
typeset +x x=${FUNCNAME[0]}
echo "$x, $*"
EOFB
function f {
typeset x=${FUNCNAME[0]}
x= command . /dev/fd/3 4 5 6; echo "$x, $*"
}
f 1 2 3
EOFA
source, 4 5 6
f, 1 2 3