Is there something like Command Substitution in Windows CLI?

14

3

In Linux (Bash), there's a way to use a command as a parameter for another command, using back-ticks:

> echo ===== `time` =====

This would print:

===== The current time is: 12:22:34.68 =====

Is there a way to do this in cmd.exe on WIndows ?

Cristi Diaconescu

Posted 2011-05-27T09:25:48.107

Reputation: 2 810

1

see this post

– Prince John Wesley – 2011-05-27T09:38:26.860

Also see this this post (use of doskey command from cmd)

– misterjaytee – 2011-05-27T11:00:03.813

@misterjaytee: Command substitution and aliases are different things. – user1686 – 2011-05-27T13:59:49.700

@grawity - Thanks for pointing that out - Note to self: must read the question properly before responding... – misterjaytee – 2011-05-30T13:26:08.957

That's not what time does. – Wuffers – 2011-06-06T21:25:29.623

@Mark That's what time does on Windows... – Cristi Diaconescu – 2011-07-07T20:08:08.633

@Cristi: Linux isn't Windows. On Linux, time measures how long it takes a script to execute. – Wuffers – 2011-07-07T20:30:30.903

Answers

9

Try this:

echo. ===== %time% =====

I know this may not be what you want, because you mentioned command substitution... So this may be it:

for /f "usebackq tokens=*" %i in (`date/t&time/t`) do echo.  ===== %i =====

For more hints about the usage of usebackq try this command:

for /?

Kurt Pfeifle

Posted 2011-05-27T09:25:48.107

Reputation: 10 024

4Yep, for /f is what I was looking for. Thanks! On a side note: It's so kludgy and hard to remember (compared to the bash way). I should give up "bat programming" and learn something more productive - PowerShell maybe? – Cristi Diaconescu – 2011-07-07T20:10:15.417

3

In Windows the '( )' operator has a similar behavior as the Bash command substitution.

This Linux script:

my_linux_variable=$(ls)
my_alternate_linux_variable=`ls`

echo $my_linux_command=$(ls)
echo $my_alternate_linux_command=`ls`

gives a similar result as Windows PowerShell:

$my_windowsPS_variable = (dir)

$my_windowsPS_variable

and as Windows CMD:

set my_windowsCMD_variable=(dir)
%my_windowsCMD_variable%

DDS

Posted 2011-05-27T09:25:48.107

Reputation: 514

9Windows CMD example is wrong. Parens in cmd shell just execute a command in a subshell. The env var is set to "(dir)" and it is executed on the second line (when the env var is surrounded by %) - not really the substitution you want. – davidbak – 2017-03-02T17:41:40.260

1this is incorrect for windows cmd.exe behavior – JJS – 2019-01-07T18:33:38.137

This is powershell, whereas the question is about cmd.exe – Raúl Salinas-Monteagudo – 2019-07-25T08:37:47.340

0

No, but here is the workaround:

D:\>time /t
08:18 PM

D:\>time /t > time.tmp

D:\>set /p time=<time.tmp

D:\>echo == %time% ==
== 08:18 PM ==

See also: Batch equivalent of Bash backticks.

kenorb

Posted 2011-05-27T09:25:48.107

Reputation: 16 795