为什么 sh/bash 在尝试设置环境变量时会设置命令行参数值?

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

Why does sh/bash set command line parameter values when trying to set environment variable?

bashshellenvironment-variablescommand-line-argumentssh

提问by Touko

A question on basics : While tuning environment variables for a program launched from a script, I ended up with somewhat strange behaviour with sh (which seems to be actually linked to bash) : variable setting seems to mess up with command-line parameters.

关于基础知识的问题:在为从脚本启动的程序调整环境变量时,我最终对 sh 产生了一些奇怪的行为(这似乎实际上与 bash 相关联):变量设置似乎与命令行参数混淆。

Could somebody explain why does this happen?

有人可以解释为什么会发生这种情况吗?

A simple script:

一个简单的脚本:

#! /bin/sh

# Messes with  ??
set ANT_OPTS=-Xmx512M
export ANT_OPTS

# Works
# export ANT_OPTS=-Xmx512M

echo "0 = 
$ ./test.sh foo
0 = ./test.sh
1 = ANT_OPTS=-Xmx512M
" echo "1 = "

When I run this with the upper alternative (set + export), the result is as following:

当我使用上层替代(set + export)运行它时,结果如下:

$ ./test.sh foo
0 = ./test.sh
1 = foo

But with lower alternative (export straight), the result is as I supposed:

但是使用较低的替代方案(直接导出),结果正如我所想的:

ANT_OPTS=-Xmx512m
export ANT_OPTS 

There is surely logical explanation, I just haven't figured it out yet. Somebody who does have idea?

肯定有合乎逻辑的解释,只是我还没有弄清楚。有人有想法吗?

br, Touko

br,东子

回答by Hank Gay

You should just use ANT_OPTS=-Xmx512Minstead of set ANT_OPTS=-Xmx512M.

你应该只使用ANT_OPTS=-Xmx512M而不是set ANT_OPTS=-Xmx512M.

UPDATE: See herefor discussion of set, and the manual.

更新:有关和手册的讨论,请参见此处set

回答by Paul Tomblin

"set" isn't part of setting variables in Bourne Shell. That should be

“set”不是在 Bourne Shell 中设置变量的一部分。那应该是

##代码##