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

发布于 2024-09-03 01:05:13 字数 554 浏览 8 评论 0原文

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

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

一个简单的脚本:

#! /bin/sh

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

# Works
# export ANT_OPTS=-Xmx512M

echo "0 = $0"
echo "1 = $1"

当我使用上面的替代方案(设置+导出)运行它时,结果如下:

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

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

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

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

br、图子

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.

Could somebody explain why does this happen?

A simple script:

#! /bin/sh

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

# Works
# export ANT_OPTS=-Xmx512M

echo "0 = $0"
echo "1 = $1"

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

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

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

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

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

br, Touko

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

难如初 2024-09-10 01:05:13

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

更新:请参阅此处了解set的讨论和手册

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

UPDATE: See here for discussion of set, and the manual.

穿透光 2024-09-10 01:05:13

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

ANT_OPTS=-Xmx512m
export ANT_OPTS 

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

ANT_OPTS=-Xmx512m
export ANT_OPTS 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文