我的目的是使用当前脚本文件中其他脚本文件的变量。
我使用source
例如,
我有两个文件,test.sh
和test1.sh
在test.sh
中,我有:
hello="hello world"
在test1.sh
中,我这样做:
source test.sh
echo "$hello"
但如果我在hello
中有一个名为test1
的变量怎么办?
我发现,如果我source
之后的变量声明如下:
hello= "Good bye world"
source test.sh
echo "$hello"
我会得到,
hello world
但如果这样做,
source test.sh
hello= "Good bye world"
echo "$hello"
我会得到,
Good bye world
对我来说,这对我来说非常不方便,因为我必须照顾我使用source
的位置,如果我想在这两个变量之间切换,可能需要反复这样做。
如何解决这个问题?
例如,我想做这样的事情,
echo $hello(of the localone) $hello(of the sourced one)
有可能吗?
答案 0 :(得分:1)
执行source test.sh
时,就像将整个test.sh复制粘贴到执行中一样。
这样做
hello= "Good bye world"
source test.sh
echo "$hello"`
相当于
hello= "Good bye world"
hello="hello world"
echo "$hello"
正在做
source test.sh
hello= "Good bye world"
echo "$hello"
相当于
hello="hello world"
hello= "Good bye world"
echo "$hello"
在这两种情况下,hello
的值都被指定两次。第二个值将覆盖第一个值。
您最好的选择是在文件中使用不同的变量名称,例如test.sh中的hello
和test1.sh中的hello1
答案 1 :(得分:0)
答案是否这是不可能的。
Shell没有提供任何处理变量名称空间冲突的机制。
注意:korn-shell确实提供了一个命令(不属于POSIX,不受其他人支持) namespace
来处理这个特殊问题。这在question at unix.stackexchange
echo 'function hi { echo Ahoj, světe\!; }' > czech.ksh
echo 'function hi { echo Hello, World\!; }' >english.ksh
namespace english { . ./english.ksh; }
namespace czech { . ./czech.ksh; }
.english.hi; .czech.hi
此行为在此comparison of different unix shells中提及 这个旧bash FAQ。