Windows 批处理文件中一行上的多个命令

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

Multiple commands on a single line in a Windows batch file

windowsbatch-file

提问by Raghuram

In Unix, we can put multiple commands in a single line like this:

在 Unix 中,我们可以将多个命令放在一行中,如下所示:

$ date ; ls -l ; date

I tried a similar thing in Windows:

我在 Windows 中尝试过类似的事情:

 > echo %TIME% ; dir ; echo %TIME

But it printed the time and doesn't execute the command dir.

但它打印了时间并且不执行命令dir

How can I achieve this?

我怎样才能做到这一点?

回答by paxdiablo

Use:

用:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bashand other UNIXy shells.

根据记忆,这相当于bashUNIXy shell 和其他 UNIXy shell 中的分号分隔符。

There's also &&(or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand &is what you're looking for here.

还有&&(or ||) 只有在第一个成功(或失败)的情况下才执行第二个命令,但单个 & 符号&正是您在这里寻找的。



That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

但是,这可能会给您相同的时间,因为环境变量往往在读取而不是执行时进行评估。

You can get round this by turning on delayed expansion:

您可以通过打开延迟扩展来解决这个问题:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

这是命令行所需要的。如果您在脚本中执行此操作,则可以使用setlocal

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal