Windows 批处理文件中一行上的多个命令 [英] Multiple commands on a single line in a Windows batch file

查看:26
本文介绍了Windows 批处理文件中一行上的多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

$ date ; ls -l ; date

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

I tried a similar thing in Windows:

 > echo %TIME% ; dir ; echo %TIME

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

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

我怎样才能做到这一点?

How can I achieve this?

推荐答案

使用:

echo %time% & dir & echo %time%

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

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

还有 &&(或 ||),它只在第一个命令成功(或失败)时才执行第二个命令,但是单个 & 符号 & 就是您在此处寻找的内容.

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.

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

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

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

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

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

这篇关于Windows 批处理文件中一行上的多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆