bash 脚本中的源文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16011245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:35:24  来源:igfitidea点击:

Source files in a bash script

bashshellubuntu

提问by user408041

I am using two versions of ROS next to each other. To use one I have to source some environment variables for the specific version. I would like to create a script that does this. But if I create a script like below the variables are not set, they are probably set in a subshell. How can I source the files to the main terminal shell?

我正在使用彼此相邻的两个版本的 ROS。要使用一个,我必须为特定版本提供一些环境变量。我想创建一个执行此操作的脚本。但是如果我创建一个像下面这样的脚本,变量没有设置,它们可能是在子shell中设置的。如何将文件提供给主终端外壳?

source.sh:

源文件:

source /opt/ros/fuerte/setup.bash;
source  ~/fuerte_workspace/setup.bash;

Here is how i am calling source.sh:

这是我调用 source.sh 的方式:

./source.sh
# This does not echo anything, but I expect it should
echo $ros_config


Update: By sourcing source.sh as suggested in the answer, I can now see the variables being set.

更新:通过按照答案中的建议采购 source.sh,我现在可以看到正在设置的变量。

source ./source.sh
# This works now
echo $ros_config

回答by MangeshBiradar

Execute Shell Script Using . ./ (dot space dot slash)

使用 . ./(点空间点斜线)

While executing the shell script using “dot space dot slash”, as shown below, it will execute the script in the current shell without forking a sub shell.

使用 执行 shell 脚本时“dot space dot slash”,如下所示,它将在当前 shell 中执行脚本,而不会分叉子 shell。

$ . ./setup.bash

In other words, this executes the commands specified in the setup.bashin the current shell, and prepares the environment for you.

换句话说,这将执行setup.bash当前 shell 中指定的命令,并为您准备环境。

回答by anubhava

Use dot notation to source in the script file in the currentshell i.e. without creating a sub-shell:

使用点符号在当前shell中的脚本文件中获取源代码,即不创建子 shell

. /opt/ros/fuerte/setup.bash
. ~/fuerte_workspace/setup.bash