Cygwin Bash 中的命令行变量分配不起作用?
根据 Bash 手册第 3.7.1 节,命令行开头的变量分配应该对调用的程序可见。
例如,
DIR=/tmp ls $DIR
应该表现得就像我输入了“ls /tmp” - 并且变量 DIR 在执行命令后不应保留。
Cygwin Bash(GNU bash,版本 3.2.51(24)-release (i686-pc-cygwin))似乎不会执行此操作 - 上述命令的行为就像未定义 $DIR 一样。其他测试(例如“DIR=/tmp echo $DIR”、“DIR=/tmp set”等)证实了这一点。
请注意,添加分号有效(“DIR=/tmp ; ls $DIR”),但会保留变量在命令之后定义。
为什么这没有按预期工作?
According to section 3.7.1 of the Bash manual, variable assignments at the beginning of a command line should be visible to the invoked program.
e.g.
DIR=/tmp ls $DIR
should behave as if I've typed "ls /tmp" - and the variable DIR should not persist after executing the command.
Cygwin Bash (GNU bash, version 3.2.51(24)-release (i686-pc-cygwin)) appears not to do this - the above command behaves as if $DIR is not defined. This is confirmed by other tests such as "DIR=/tmp echo $DIR", "DIR=/tmp set" etc.
Note that adding a semicolon works ("DIR=/tmp ; ls $DIR"), but leaves the variable defined after the command.
Why is this not working as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它确实有效——但不是在你试图让它发挥作用的情况下。
环境变量 DIR 是为 ls 设置的 - 但当 shell 扩展命令的 $DIR 时不会设置。这就是 Bourne shell 的行为方式;这就是它的后继者(例如 Korn shell 和 Bash)的行为方式。
您可以看到 DIR 是通过将 ls $DIR 更改为 env 来设置的;这将显示外部(非内置)命令的环境。
在这个例子中,想一想:与以下内容相比,您输入的内容多了 9 个字符:
如果您必须设置并删除它,那么这样做就可以了:
该变量在 shell 计算
ls 之前设置$DIR
,但整个命令在子 shell 中运行,因此对调用 shell 没有影响。It does work - but not in the context that you are trying to make it work.
The environment variable DIR is set for
ls
- but is not set when the shell expands the $DIR of the command. This is the way the Bourne shell behaved; it is the way its successors such as the Korn shell and Bash behave.You could see that DIR is set by changing
ls $DIR
toenv
; that would show the environment of an external (not built-in) command.In this example, think about it for a moment: what you've typed is 9 extra characters compared with:
If you must have it set and removed, then this does the trick:
The variable is set before the shell evaluates
ls $DIR
, but the whole command is run in a sub-shell so it has no impact on the invoking shell.