为什么 sh/bash 在尝试设置环境变量时设置命令行参数值?
关于基础知识的问题:在调整从脚本启动的程序的环境变量时,我最终遇到了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该只使用
ANT_OPTS=-Xmx512M
而不是set ANT_OPTS=-Xmx512M
。更新:请参阅此处了解
set
的讨论和手册。You should just use
ANT_OPTS=-Xmx512M
instead ofset ANT_OPTS=-Xmx512M
.UPDATE: See here for discussion of
set
, and the manual.“set”不是 Bourne Shell 中设置变量的一部分。那应该是
"set" isn't part of setting variables in Bourne Shell. That should be