bash shell 脚本中的“源”命令不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48785324/
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-18 16:49:53  来源:igfitidea点击:

"source" command in shell script not working

bashshellcommand-line-interfacesh

提问by RETELLIGENCE

I have a file to be sourced in Centos 7. It just works fine if I do :

我有一个要在 Centos 7 中获取的文件。如果我这样做,它就可以正常工作:

$ source set_puregev_env

however, if I put this in a shell script, it doesn't work..

但是,如果我把它放在一个 shell 脚本中,它就不起作用了..

$ sh xRUN 
xRUN: line 3: source: set_puregev_env: file not found

this is my shell script : xRUN

这是我的 shell 脚本:xRUN

#!/bin/bash

source set_puregev_env

can anyone tell me what I might be doing wrong, or missing?

谁能告诉我我可能做错了什么或遗漏了什么?

回答by stalet

source is a command implemented in bash, but not in sh. There are multiple ways to fix your script. Choose either one.

source 是在 bash 中实现的命令,但不是在 sh 中。有多种方法可以修复您的脚本。选择其中之一。

Run the script using bash interpreter

使用 bash 解释器运行脚本

When you are invoking the xRUNscript - you are explicitly telling it to be interpreted by sh

当您调用xRUN脚本时 - 您明确地告诉它由sh

$ sh xRUN 

To change and interpret the script with bash instead do

要使用 bash 更改和解释脚本,请执行以下操作

$ bash xRUN 

This will make bash interpret the source command, and your script will work.

这将使 bash 解释源命令,并且您的脚本将起作用。

Use dot command to make script bourne compatible

使用 dot 命令使 script bourne 兼容

You can also change the source with a dot command which does the same thing but is supported in both bourne and bash.

您还可以使用 dot 命令更改源,该命令执行相同的操作,但在 bourne 和 bash 中均受支持。

Change the line:

更改行:

source set_puregev_env

With:

和:

. set_puregev_env 

Now the script will work with either sh or bash.

现在脚本可以使用 sh 或 bash。

Make script executable

使脚本可执行

You should also run the script directly to avoid confusions like these by making it executable chmod +x xRUN, and invoking it like this:

您还应该直接运行该脚本,通过将其设置为可执行chmod +x xRUN并像这样调用它来避免此类混淆:

$ ./xRUN

It will then use the command specified in the shebang and use the rest of the script as input. In your case it will use bash - since that is specified in the shebang.

然后它将使用在shebang 中指定的命令并使用脚本的其余部分作为输入。在您的情况下,它将使用 bash - 因为这是在 shebang 中指定的。