在多个脚本中定义公共变量? [英] Defining common variables across multiple scripts?

查看:123
本文介绍了在多个脚本中定义公共变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多Bash和Perl脚本,它们在功能上无关,但是相互关联,因为它们在同一项目中工作. 它们在同一项目中工作的事实意味着,我通常在每个脚本的顶部指定相同的目录,相同的项目特定命令,相同的关键字.

I have a number of Bash and Perl scripts which are unrelated in functionality, but are related in that they work within the same project. The fact that they work in the same project means that I commonly specify the same directories, the same project specific commands, the same keywords at the top of every script.

当前,这还没有使我感到痛苦,但是我知道将所有这些值放在一个位置会更容易,然后,如果发生某些更改,我可以一次更改一个值,并让各种脚本来应对这些更改.

Currently, this has not bitten me, but I understand that it would be easier to have all of these values in one place, then if something changes I can change a value once and have the various scripts pick up on those changes.

问题是-如何最好地声明这些值?每个脚本中必需"的单个Perl脚本将需要对Perl脚本进行较少的更改,尽管并不能为Bash脚本提供解决方案.使用键=值"格式的配置文件可能会更通用,但需要每个脚本来解析配置,并且有可能引入问题.有更好的选择吗?使用环境变量?还是Perl可以轻松执行和解释的特定于Bash的方式?

The question is - how is best to declare these values? A single Perl script that is 'required' in each script would require less changes to the Perl scripts, though doesn't provide a solution to the Bash script. A configuration file using a "key=value" format would perhaps be more universal, but requires each script to parse the configuration and has the potential to introduce issues. Is there a better alternative? Using environmental variables? Or a Bash specific way that Perl can easily execute and interpret?

推荐答案

运行shell脚本时,它是在子shell中完成的,因此不会影响父shell的环境.因此,当您将变量声明为key=value时,其作用域仅限于子Shell上下文.您想通过以下方式来获取脚本的源代码:

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. So when you declare a variable as key=value its scope is limited to the sub-shell context. You want to source the script by doing:

. ./myscript.sh

这将在当前外壳程序的上下文中执行它,而不是作为子外壳程序.

This executes it in the context of the current shell, not as a sub shell.

在bash手册页中:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename. 

还可以使用export命令创建全局环境变量. export控制哪些变量可用于新进程,所以如果您说

Also you can use the export command to create a global environment variable. export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./myscript2.sh

然后$BAR将在myscript2.sh的环境中可用,但$FOO则不可用.

then $BAR will be available in the environment of myscript2.sh, but $FOO will not.

这篇关于在多个脚本中定义公共变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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