3

I have a command that adds the timestamp at the beginning and the end (echo %time% & #other command# & echo %time%). However, the %time% will be the same, regardless of how long the command took to execute.

example output:

Time start: 19:48:31.75

Pinging google.com [2a00:1450:400e:80c::200e] with 32 bytes of data:
Reply from 2a00:1450:400e:80c::200e: time=13ms
Reply from 2a00:1450:400e:80c::200e: time=13ms
Reply from 2a00:1450:400e:80c::200e: time=9ms
Reply from 2a00:1450:400e:80c::200e: time=10ms

Ping statistics for 2a00:1450:400e:80c::200e:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 9ms, Maximum = 13ms, Average = 11ms

Time end: 19:48:31.76

Is there a way to have this work, still within one line?

Thanks

JessaCrow
  • 31
  • 1
  • command & command execution is only when true, why not use semicolon ; it execute regardless – djdomi Aug 14 '21 at 18:19
  • @djdomi i tried this, but writing it like `echo %time%; ping google.com; echo %time%` or even with quotes, it doesn't work. It sees the semicolon as a part of the command, rather than closing it – JessaCrow Aug 14 '21 at 18:23
  • @djdomi `;` does no work in cmd, a single `&` continues execution while `&&` does not – NiKiZe Aug 14 '21 at 18:23
  • 1
    @MichaelHampton: The difference is .01 seconds while it shoud be more than 4 seconds. – Esa Jokinen Aug 15 '21 at 07:44

1 Answers1

2

CMD expands variables and then executes each line. That means that

echo %time% & ping 127.0.0.1 & echo %time%

is first expanded, and then executed

There is also "delayed expansion" Here is some example usage, and even more detailed This however only works in a cmd file, and not on commandline

setlocal ENABLEDELAYEDEXPANSION
echo !time! & ping 127.0.0.1 & echo !time!

Continue searching maybe cmd /V can be used:

cmd /V /C "echo %time% & ping 127.0.0.1 & echo !time!"

It gives expected result for me, but there might be gotchas preventing some use cases.

It Wasn't Me
  • 103
  • 3
NiKiZe
  • 1,246
  • 8
  • 20
  • *[... and even more detailed](https://superuser.com/questions/1569594/how-does-delayed-expansion-works-in-batch-script)* I liked the support reference.... d:) – It Wasn't Me Aug 27 '21 at 01:21
  • I am in my mac now, so no way to tes, but. maybe **`call`** can do this too: `echo %time% & ping 127.0.0.1 & call echo %time%`... – It Wasn't Me Aug 27 '21 at 01:22
  • @It that will not work since the variables is evaluated first there as well, you must have the delayed expansion if you run it on same line (or block `()`) – NiKiZe Aug 27 '21 at 10:19
  • for this i write *maybe* – It Wasn't Me Aug 27 '21 at 10:24