bash 使用 exec 执行命令来设置变量

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

Setting variables with executing a command with exec

bashsyntaxexec

提问by Ken

You can set a variable for a single command like this:

您可以为单个命令设置一个变量,如下所示:

MY_VARIABLE=my_value ./my_script.sh

You can hand off to another script like this:

您可以像这样移交给另一个脚本:

exec ./my_script.sh

But when I try to do both like this:

但是当我尝试这样做时:

exec MY_VARIABLE=my_value ./my_script.sh

I get an error:

我收到一个错误:

exec: MY_VARIABLE=my_value: not found

Why is that?
Is there any way to do this?

这是为什么?
有没有办法做到这一点?

回答by devnull

You need to use envto specify the environment variable:

您需要使用env来指定环境变量:

exec env MY_VARIABLE=my_value ./my_script.sh

If you want your script to start with an empty environment or with only the specified variables, use the -ioption.

如果您希望脚本以空环境或仅使用指定变量开始,请使用该-i选项。

From man env:

来自man env

   env - run a program in a modified environment

回答by rici

In bash, you can set environment variables for a command by putting the assignments at the beginning of the command. This works the same for execas any other command, so you write:

在 bash 中,您可以通过将赋值放在命令的开头来为命令设置环境变量。这exec与任何其他命令的工作原理相同,因此您可以编写:

MYVARIABLE=my_value exec ./my_script.sh