在外部脚本变量的声明 [英] Declaring variables in external script

查看:124
本文介绍了在外部脚本变量的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绑写它使用在另一个脚本中声明的变量的脚本。
我试过到目前为止使用导出来定义环境变量或只使用本地的。

I'm tying to write a script which uses variables declared in another script. I've tried so far using export to define environmental variables or just using local ones.

所以,我有我的配置脚本:

So I have my config script:

export DIR_STORAGE="/var/storage/"

和脚本试图在同一目录中使用它:

And script trying to use it in the same directory:

source conf.sh
echo "DIR="${DIR_STORAGE}

但似乎并没有工作。我该如何解决这个问题?

but that doesn't seem to work. How can I fix this?

推荐答案

即使你有在同一目录下两个文件,​​源conf.sh 将寻找的conf。 SH在当前目录的。例如:

Even if you have both files in the same directory, source conf.sh will look for conf.sh in the current directory. For example:

SHELL$ pwd
/home/user

SHELL$ ls mydir/
script.sh conf.sh

SHELL$ mydir/script.sh
script.sh: line 1: conf.sh: No such file or directory

在这种情况下,该脚本将寻找'conf.sh在当前的(家)目录,而不是在MYDIR。

In this case, the script will look for 'conf.sh' in the current (home) directory, not under mydir.

要避免这一点,总是寻找在剧本同一目录下的配置文件,常见的做法是使用:

To avoid this and always look for the config file in the same directory where the script is, a common practice is to use:

source "$(dirname $0)/conf.sh"

这将提取从用来调用脚本并追加config文件名给它的命令路径;在上面的例子中,这将成为源MYDIR / conf.sh这应该很好地工作。

This will extract the path from the command you used to invoke the script and append the config file name to it; in the example above, this will become source "mydir/conf.sh" which should work fine.

P.S。如果你使用有没有必要导出的任何变量。

P.S. If you use source there's no need to export any variables.

这篇关于在外部脚本变量的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆