如何删除 cmd 变量?
假设我在 CMD shell 中执行以下命令:
SET "FOO=bar"
除了回收 CMD shell 之外,还有其他方法可以取消定义此变量吗?
Let's say I execute the following in the CMD shell:
SET "FOO=bar"
Is there a way to undefine this variable, other than recycling the CMD shell?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,您可以使用以下命令取消设置
或显式使用:
确保
=
符号后面没有尾随的无关(不可见)字符。即:set FOO=
与set FOO=
不同。Yes, you can unset it with
Or explicitly using:
Ensure no trailing extraneous (invisible) characters come after the
=
sign. That is:set FOO=
is different fromset FOO=
.取消设置变量的一种安全方法是同时使用引号,这样就不会出现尾随空格的问题。
A secure way to unset the variable is to use also quotes, then there aren't problems with trailing spaces.
另一种方法
注意:这不适用于交互式命令提示符。但适用于批处理脚本。
another method
Note: This would not work on an interactive command prompt. But works in batch script.
这在我的 Windows 7 CMD shell 中适用于我:
This works for me in my Windows 7 CMD shell:
我只想提供以下内容作为评论,但我认为它本身就足够重要。
之前的很多答案都提到需要注意尾随空格;确实如此。然而,我发现有时尾随空格无论如何都想进入那里 - 特别是如果您正在执行命令行单行并且需要空格作为命令分隔符。
这是该问题的解决方案:
通过将声明用双引号引起来,可以完全避免间距问题。当通过连接来消除之间的空格(例如路径)来创建变量时,这也非常有用,例如:
I would offer the following only as a comment, but I think it's important enough to stand on its own.
A lot of the previous answers mentioned that one needs to beware of trailing spaces; and for sure that is true. However I've found that sometimes trailing spaces just want to get in there no matter what - particularly if you are doing a command line one-liner and need the space as a command separator.
This is the solution to that problem:
By wrapping the declaration in double quotes that way, the spacing issue can be avoided entirely. This can also really useful when variables are created by concatenating to eliminate spaces in between - for example - paths, e.g: