如何定义Shell脚本变量以使其在脚本之外 [英] How do I define a shell script variable to have scope outside of the script

查看:202
本文介绍了如何定义Shell脚本变量以使其在脚本之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ubuntu Natty.

I'm using Ubuntu Natty.

我有一个已保存到/etc/init.d/qstart的shell脚本. Shell脚本包含以下内容:

I have a shell script which I have saved to /etc/init.d/qstart. The shell script contains the following:

apt-get -y update
apt-get -y upgrade
apt-get -y install tofrodos gcc make nmap lsof expect sysstat
dbpass="mydbpassword"

但是,执行脚本后,我想测试是否设置了dbpass,然后在提示符下输入echo $dbpass.但它是空的.

However, after I execute the script, I want to test that dbpass is set and I enter echo $dbpass in the prompt. But it's empty.

如何在shell脚本中定义变量,以便可以在变量外部访问它?!

How do I define a variable in my shell script so that I can access it outside of it?!

谢谢.

推荐答案

您不能在父进程的环境中设置变量.您只能设置当前流程的环境或为流程的子级准备环境.

You can't set variables in parent process's environment. You can only set your current process's environment or prepare an environment for your process's children.

也就是说,您可以指示Shell在当前Shell进程中从脚本运行命令,而不是派生新的Shell.您可以这样做:

That said, you can instruct your shell to run commands from a script in the current shell process rather than forking a new shell. You can do it like this:

source your_script.sh

. your_script.sh

(注意点后的空格).由于your_script.sh中的命令是由当前shell运行的,因此保留了脚本中对环境所做的更改.

(note the space after the dot). Since here commands inside your_script.sh are run by the current shell the changes made to the environment inside the script are retained.

但是,如果运行脚本的shell不是您要在其中使用环境变量的shell的祖先,那么根本就没有办法使用环境变量来实现您的目标.例如,如果您的脚本是由一些没有孩子的外壳程序在初始化时运行的,那么完成的所有环境设置都会永久地不可逆转地丢失.在这种情况下,请使用其他机制,例如文件(也许在/var下的某个位置).

However, if the shell running your script is not an ancestor of the shell in which you wish to use the environment variable then there is no way to achieve your goal using environment variables at all. For example, if you script is run at initialization by some childless shell all environment settings done there are irreversibly lost forever. In this case, use some other mechanism like a file (perhaps somewhere under /var).

如果希望给定外壳的所有实例在其环境中设置某些变量,则可以使用大多数外壳使用的初始化脚本.通常,它们具有系统范围和每个用户的初始化脚本.例如,bash使用/etc/profile作为交互式登录shell的系统范围的初始化脚本,并使用$HOME/.bash_profile(也包括$HOME/.bash_login$HOME/.profile)作为每个用户的初始化脚本.有关特定于bash的详细信息,请参见此参考.如果您使用其他外壳,请尝试使用其各自的手册.

If you want all instances of a given shell to have certain variables set in their environment you can use initialization scripts that most shells use. Usually, they have a system-wide and per-user initialization scripts. For example, bash uses /etc/profile as system-wide initialization script for interactive login shell and $HOME/.bash_profile (also $HOME/.bash_login and $HOME/.profile) as per-user initialization script. See this reference for bash-specific details. If you use a different shell, try its respective manual.

这篇关于如何定义Shell脚本变量以使其在脚本之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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