简体   繁体   English

关于外壳变量和环境变量

[英]about shell variables and environment variables

I'm reading Wrox, Beginning Linux Programming. 我正在阅读Wrox,《开始Linux编程》。 But I've got a question about shell variables. 但是我有一个关于shell变量的问题。

Here is a shell script named test.sh: 这是一个名为test.sh的shell脚本:

#! /bin/bash
read test
echo $test
exit 0

Then I chmod the script: 然后我修改脚本:

$ chmod +x test.sh
$ ./test,sh

When I type "ok", it echos the "ok". 当我键入“确定”时,它会回显“确定”。

But when I returned to the shell interface, I typed: 但是,当我返回shell界面时,我输入了:

$ echo $test

It returned nothing... 它什么也没返回...

I don't know why $test doesn't return "ok" just like the script does... And the book doesn't metion it... 我不知道为什么$ test不会像脚本一样返回“ ok”……而书没有提及它……

Thanks in advance:) 提前致谢:)

The variables only exist in the process where they were created (and also in child processes, if they are exported). 变量仅存在于创建它们的过程中(如果存在,则还存在于子过程中)。 Running a script creates a new process, after the script ends, all its variables are lost. 运行脚本会创建一个新进程,脚本结束后,所有变量均会丢失。

You can run the script without starting a new process by "sourcing" it: 您可以通过“采购”脚本来运行脚本,而无需启动新进程:

. ./test.sh

You should remove the exit then, though, otherwise it will exit your current shell. 但是,您应该删除exit ,否则它将退出当前的外壳。

It is because they are different processess, to "include" source of other script run 这是因为它们是不同的过程,以“包含”其他脚本运行的源

. test.sh

the test.sh should be without exit: test.sh应该没有退出:

#! /bin/bash
read test
echo $test

Process locality 流程局部性

The values of environment variables are local, which means they are specific to the running process in or for which they were set. 环境变量的值是本地的,这意味着它们特定于设置它们或为其设置的正在运行的进程。 This means that if we open two terminal windows (which means we have two separate bash processes running), and change a value of an environment variable in one of the windows, that change will not be seen by the shell in the other window or any other program currently on the desktop. 这意味着,如果我们打开两个终端窗口(这意味着我们有两个单独的bash进程正在运行),并在其中一个窗口中更改环境变量的值,则该更改将不会在另一个窗口或任何其他窗口中被shell看到。当前在桌面上的其他程序。

For your more understanding : https://help.ubuntu.com/community/EnvironmentVariables 为了您的更多理解: https : //help.ubuntu.com/community/EnvironmentVariables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM