How do I run two commands in one line in Windows CMD?
Asked Answered
T

24

1342

I want to run two commands in a Windows CMD console.

In Linux I would do it like this

touch thisfile ; ls -lstrh

How is it done on Windows?

Tarrel answered 8/11, 2011 at 18:31 Comment(0)
B
1892

Like this on all Microsoft OSes since 2000, and still good today:

dir & echo foo

If you want the second command to execute only if the first exited successfully:

dir && echo foo

The single ampersand (&) syntax to execute multiple commands on one line goes back to Windows XP, Windows 2000, and some earlier NT versions. (4.0 at least, according to one commenter here.)

There are quite a few other points about this that you'll find scrolling down this page.

Historical data follows, for those who may find it educational.

Prior to that, the && syntax was only a feature of the shell replacement 4DOS before that feature was added to the Microsoft command interpreter.

In Windows 95, 98 and ME, you'd use the pipe character instead:

dir | echo foo

In MS-DOS 5.0 and later, through some earlier Windows and NT versions of the command interpreter, the (undocumented) command separator was character 20 (Ctrl+T) which I'll represent with ^T here.

dir ^T echo foo
Bryant answered 8/11, 2011 at 18:33 Comment(17)
Works on Win 8.0 and 8.1 as well.Banded
@ZaLiTHkA Can we by default, just always run with && then?Cloddish
@Fallenreaper, that does work in the straight cmd prompt as well, so I suppose it's not a bad habit to get into. :)Musky
@Cloddish Make sure that you are aware of the practical difference between the two: See Raihan's answer below.Leon
Got ya. A && B, B only will run if A is successful, whereas A & B will run B after A, no matter what the outcome of A is. Thanks for the heads upCloddish
somehow I cannot make this working in one line: set myvar=myval && echo %myvar% . The myvar is not set immediately, or at least echo cannot fetch it. Only with separate call "echo %myvar%" it shows the correct valueBlackandblue
@Blackandblue That's a different issue. Both commands are run, but the environment variable substitutions are evaluated before either command is actually executed. So echo %myvar% will be run as echo OldValueOfMyVar. This problem can be resolved by using the Delayed Expansion feature (only available in batch files though). So try the following inside a batch file: setlocal EnableDelayedExpansion && set MyVar=MyVal && echo !MyVar! && endlocal. (NOTE: The feature requires you to use ! marks in place of the % symbols.Nibelungenlied
And if you as me thought PowerShell is the same as a Terminal, then semicolon ; is the way to go in PowerShellSchreiber
Here's also a little gem... when using variable assignment on the same line, always put the "&' right after the value, i.e, no space or windows will assign the value plus the space (s). code Bad as variable b will contain "3 " set b=3 & echo "%b" The proper way would be: set b=3& echo "%b" code Note that using quotes to display the value, will show you exactly what you are getting.Omnivorous
@Omnivorous Or use double-quotes to avoid stray spaces, as in set "b=3" & ....Thereof
Use start if you wanna run two applications at once. The command in the answer will not run the second app until the first one terminates. If the first one is a GUI app, you have to close it before running the second, which may not what you want.Ineslta
Correct. The question was regarding the Linux shell's ; operator, which runs things sequentially. If you want to run things in parallel like the Linux shell's & operator, you have to use START on Windows. There's also a way to wait for your processes to exit: https://mcmap.net/q/13955/-execute-multiple-batch-files-concurrently-and-monitor-if-their-process-is-completed And of course, PowerShell might be appropriate for more complex scenarios anyway.Bryant
I'm surprised no one has commented on if here, cuz it's tricky. @GreenRaccoon23 commented below on @Raihan's answer. Everything after the if condition is part of the then-clause even if it has a &. So if exist c:\ echo 1 & echo 2 runs both, and if not exist c:\ echo 1 & echo 2 runs neither. But @GreenRaccoon23's suggestion (if not exist c:\ echo 1) & echo 2 works; it runs 2 regardless.Dworman
For me the single $ does not do what I would like. I have the following command if exist "dist/admin-ui" rmdir /Q /S "dist/admin-ui" & cd ./client && npm ci && npm run build. If the dist/admin-ui does not exists, the command stops and does not execute the rest from cd ./client onwards. Any suggestions how to make it work ?Handwork
I would use a batch file for this if constrained to CMD, but I prefer PowerShell or some other kind of shell script for complex operations. Use IF/ELSE blocks for clarity if you need multiple statements to execute as part of a conditional. See examples here. en.wikibooks.org/wiki/Windows_Programming/Programming_CMD#ELSE As for design, I do my preflight checks as early as possible, and bail at the earliest opportunity rather than having a bunch of nested conditions leading to the end result. Node can be difficult on the Windows ecosystem. I'd suggest switching to WSL2 and bash.Bryant
Is the CTRL-T (^T) command delimiter specified in a registry setting?? I can't get it to work in Windows 11 Enterprise 22H2. The AMPERSAND and PIPE delimiters still work as they used to.Pageboy
@mnemotronic: No, it's no longer part of the command interpreter. It was only a thing in MS-DOS 5 through a few early Windows NT versions.Bryant
R
705

A quote from the documentation:

Using multiple commands and conditional processing symbols

You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.

For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.

You can use the special characters listed in the following table to pass multiple commands.

  • & [...]
    command1 & command2
    Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

  • && [...]
    command1 && command2
    Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.

  • || [...]
    command1 || command2
    Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).

  • ( ) [...]
    (command1 & command2)
    Use to group or nest multiple commands.

  • ; or ,
    command1 parameter1;parameter2
    Use to separate command parameters.

Rear answered 8/11, 2011 at 18:36 Comment(12)
Try cmd /c "echo foo & echo bar".Rear
vagrant up && vagrant ssh worked without quotation marks on Windows 10.Vanlandingham
Thanks! I didn't know about singe & - makes it asynchronous and run both in parallel. I was stuck because I was using && with is synchronous and only continues if the first succeeds!Glaucous
documentation link broken, new location technet.microsoft.com/en-us/library/bb490954.aspxAmoreta
@Glaucous & does not make the commands asynchronous or parallel. command1 & command2 will run command2 after command1 has completed. The success or failure of command1 is irrelevant.Witter
In addition you can structure your code by using temporal variable. Consider command1 && set succeeded=Yes if succeeded EQU Yes (..)Sylvia
Also, mixing & with if statements can be a little tricky. To run a command after an if statement which does not have an else statement, use (if condition command1) & command2. Do not try to use if condition (command1) & command2 because command2 will not run.Peripatetic
(command1 & command2) does not work.. e.g. start (dir cd)Civic
@Peripatetic everything after the condition is part of the then-clause. So if exist c:\ echo 1 & echo 2 runs both, and if not exist c:\ echo 1 & echo 2 runs neither. But your (if not exist c:\ echo 1) & echo 2 works. It runs 2 regardless.Dworman
That , worked for me, everything else not.Highland
this post deserved to mark as answerFonsie
To other answerers: learn how to answer by providing more detailed information like in here and you'll get the upvotes.Ewaewald
P
93

& is the Bash equivalent for ; ( run commands) and && is the Bash equivalent of && (run commands only when the previous has not caused an error).

Ponder answered 8/11, 2011 at 18:37 Comment(2)
this is also true for csh, tcsh and many more shells. I've never seen ; before in LinuxTion
@LưuVĩnhPhúc in sh-style shells, ; means to run the first command, wait for it to finish, then run the second command. & means to run the first command, put it to background, and run the second command. So both programs launch simultaneously. Note that these aren't combining symbols, they are trailing symbols to the first command; you can launch a single command in background with progname & without having a second command.Scroggins
R
28

If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):

cmd /k echo hello && cd c:\ && cd Windows
Rummer answered 12/11, 2013 at 6:39 Comment(0)
U
26

You can use & to run commands one after another. Example: c:\dir & vim myFile.txt

Urinary answered 8/11, 2011 at 18:34 Comment(0)
C
22

You can use call to overcome the problem of environment variables being evaluated too soon - e.g.

set A=Hello & call echo %A%
Couvade answered 13/3, 2016 at 11:6 Comment(6)
This works only if the variable is not already set, in which case the echo prints out the old value, not the new value. At least, this is what I observe on my Windows 7 box.Chainman
I use set A= first to make sure the variable is not set.Couvade
A better method is to use delayed expansion (setlocal EnableDelayedExpansion in a script or cmd /v). For example: timeout 5 && cmd /v /c echo !TIME! && echo %TIME%.Circle
Use ^ after the first percent to get the new value: set A=Hello & call echo %^A%Through
Thanks Nick and Nicolas for you solutions! I tried to use them in more general case, when after set there are multiple commands separated with &, and I see it works onl with additional syntactical tricks. With Nick's solution I should escape the command separator as ^&: set var=Hello & cmd /v /c echo firstUsage=!var! ^& echo secondUsage=!var!. With Nicolas's solution I should repeat call before every subcommand: set var=Hello & call echo firstUsage=%^var% & call echo secondUsage=%^var% (probably one knows how to improve this).Seize
It seems that cmd interprets everything before the ampersand (&) as belonging to the previous command, including whitespace. So the above assigns the string 'Hello ' (without the quotes). This is in particular important when adding something to the PATH variable and then run a command (something like PATH=C:\mydir & myappinmydir won't work because PATH ends with a space). Do PATH=C:\mydir& myappinmydir (no space beteen mydir and &). Also this seems to be the case with redirection so echo hallo > myfile adds a space after hallo in the file (do echo hallo> myfile instead).Ownership
G
14

In windows, I used all the above solutions &, && but nothing worked Finally ';' symbol worked for me

npm install; npm start
Guernica answered 22/2, 2022 at 11:37 Comment(3)
this doesn't work for me, since the start of second command is waiting for result of the first command (e.g. http-server --port=8081 ; ng build --watch won't work)Sentiment
@Sentiment if you are running a command that is running continuously then in that case it will keep waiting so you can either try to run these types of commands in the background or run another command separatelyGuernica
yes, that's what I specified in my answer https://mcmap.net/q/13758/-how-do-i-run-two-commands-in-one-line-in-windows-cmdSentiment
D
13

A number of processing symbols can be used when running several commands on the same line, and may lead to processing redirection in some cases, altering output in other case, or just fail. One important case is placing on the same line commands that manipulate variables.

@echo off
setlocal enabledelayedexpansion
set count=0
set "count=1" & echo %count% !count!

0 1

As you see in the above example, when commands using variables are placed on the same line, you must use delayed expansion to update your variable values. If your variable is indexed, use CALL command with %% modifiers to update its value on the same line:

set "i=5" & set "arg!i!=MyFile!i!" & call echo path!i!=%temp%\%%arg!i!%%

path5=C:\Users\UserName\AppData\Local\Temp\MyFile5
Diastyle answered 3/8, 2016 at 14:31 Comment(1)
given example didn't work for me but below one did: cmd /V:ON /c "set i=5 & set arg!i!=MyFile!i! & echo path!i!=%temp%\%arg!i!%"Polyethylene
M
8

cmd /c ipconfig /all & Output.txt

This command execute command and open Output.txt file in a single command

Maccabean answered 16/4, 2014 at 5:41 Comment(0)
D
8

So, I was trying to enable the specific task of running RegAsm (register assembly) from a context menu. The issue I had was that the result would flash up and go away before I could read it. So I tried piping to Pause, which does not work when the command fails (as mentioned here Pause command not working in .bat script and here Batch file command PAUSE does not work). So I tried cmd /k but that leaves the window open for more commands (I just want to read the result). So I added a pause followed by exit to the chain, resulting in the following:

cmd /k C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe "%1" /codebase \"%1\" & pause & exit

This works like a charm -- RegAsm runs on the file and shows its results, then a "Press any key to continue..." prompt is shown, then the command prompt window closes when a key is pressed.

P.S. For others who might be interested, you can use the following .reg file entries to add a dllfile association to .dll files and then a RegAsm command extension to that (notice the escaped quotes and backslashes):

[HKEY_CLASSES_ROOT\.dll]
"Content Type"="application/x-msdownload"
@="dllfile"

[HKEY_CLASSES_ROOT\dllfile]
@="Application Extension"

[HKEY_CLASSES_ROOT\dllfile\Shell\RegAsm]
@="Register Assembly"

[HKEY_CLASSES_ROOT\dllfile\Shell\RegAsm\command]
@="cmd /k C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\regasm.exe \"%1\" /codebase \"%1\" & pause & exit"

Now I have a nice right-click menu to register an assembly.

Deferral answered 26/1, 2015 at 20:35 Comment(1)
lifehacker.com/…Surly
V
6

Use & symbol in windows to use command in one line

C:\Users\Arshdeep Singh>cd Desktop\PROJECTS\PYTHON\programiz & jupyter notebook

like in linux we use,

touch thisfile ; ls -lstrh
Veronaveronese answered 20/5, 2020 at 7:1 Comment(0)
J
5

Well, you have two options: Piping, or just &:

DIR /S & START FILE.TXT

Or,

tasklist | find "notepad.exe"

Piping (|) is more for taking the output of one command, and putting it into another. And (&) is just saying run this, and that.

Jacquetta answered 29/4, 2017 at 23:16 Comment(3)
Could you edit your post to include some explanation what does & and | do and how they differ, if at all? Right now people unfamiliar with these concepts are unable to decide for themselves which one should be used in their cases.Hamartia
As I was. My bad. I will edit the post immediately. Appreciate it.Jacquetta
Should be "findstr" instead of just "find"Chiro
F
4

In order to execute two commands at the same time, you must put an & (ampersand) symbol between the two commands. Like so:

color 0a & start chrome.exe

Cheers!

Fighter answered 13/12, 2016 at 4:41 Comment(0)
T
4

I try to have two pings in the same window, and it is a serial command on the same line. After finishing the first, run the second command.

The solution was to combine with start /b on a Windows 7 command prompt.

Start as usual, without /b, and launch in a separate window.

The command used to launch in the same line is:

start /b command1 parameters & command2 parameters

Any way, if you wish to parse the output, I don't recommend to use this. I noticed the output is scrambled between the output of the commands.

Tarpan answered 18/3, 2017 at 11:16 Comment(0)
C
4

I was trying to create batch file to start elevated cmd and to make it run 2 separate commands. When I used & or && characters, I got a problem. For instance, this is the text in my batch file:

powershell.exe -Command "Start-Process cmd \"/k echo hello && call cd C:\ \" -Verb RunAs"

I get parse error: Parse error

After several guesses I found out, that if you surround && with quotes like "&&" it works:

powershell.exe -Command "Start-Process cmd \"/k echo hello "&&" call cd C:\ \" -Verb RunAs"

And here's the result:

Result of execution

May be this'll help someone :)

Cabbagehead answered 6/9, 2022 at 21:31 Comment(0)
G
2

Try to create a .bat ot .cmd file with those lines using doskey key and $T which is equivalent to & to do several command line in just one line :

doskey touch=echo off $T echo. ^> $* $T dir /B $T echo on

It'll create an empty file.

Example:

touch myfile

In cmd you'll get something like this:

enter image description here

But as mentioned previously by others, it is really advised to use & operator to do many command line in one line from CMD prompt.

Enjoy =)

Grubbs answered 25/11, 2020 at 21:50 Comment(2)
Useful thanks. Don't you need doskey touch=echo off $T ...Slr
@Slr Thank you ! Yes, you're totally right. Forgot it. I've just edited my comment.Grubbs
S
2

Use "&&" if you want to "chain" the commands (e.g. npm install && npm build) - the second one will wait for exit value of the first one.

If you need to run both commands at the same time without waiting for them to finish, you have to use start, e.g. start http-server && start ng build --watch.

Sentiment answered 18/10, 2023 at 10:7 Comment(0)
M
1

No, cd / && tree && echo %time%. The time echoed is at when the first command is executed.

The piping has some issue, but it is not critical as long as people know how it works.

Mystery answered 22/7, 2016 at 8:56 Comment(0)
L
1

One more example: For example, when we use the gulp build system, instead of

gulp - default > build

gulp build - build build-folder

gulp watch - start file-watch

gulp dist - build dist-folder

We can do that with one line:

cd c:\xampp\htdocs\project & gulp & gulp watch
Longsighted answered 7/5, 2017 at 14:9 Comment(0)
T
1

Yes there is. It's &.

&& will execute command 2 when command 1 is complete providing it didn't fail.

& will execute regardless.

Tuckie answered 19/4, 2019 at 3:29 Comment(0)
H
1

With windows 10 you can also use scriptrunner:

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror

it allows you to start few commands on one line you want you can run them consecutive or without waiting each other, you can put timeouts and rollback on error.

Henandchickens answered 6/11, 2020 at 21:3 Comment(0)
E
0

& and && work perfectly, as djdanlib said, but when I tried && to run a lot of setup programs consecutively it didn't wait for each one to finish before moving to the next. It works fine for command line apps and commands, but when you start a gui app (like a setup program) then windows returns success as soon as it successfully launches the program, without waiting for it to close.

I fixed this by putting a pause between each one, like this:

for %a in (*.exe) do pause && start %a

(that's supposing you want to run each .exe in the current folder one at a time)

Ellon answered 20/8, 2023 at 9:17 Comment(1)
start /wait might work (depends on how the executable is programmed)Completion
P
-2

When you try to use or manipulate variables in one line beware of their content! E.g. a variable like the following

PATH=C:\Program Files (x86)\somewhere;"C:\Company\Cool Tool";%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

may lead to a lot of unhand-able trouble if you use it as %PATH%

  1. The closing parentheses terminate your group statement
  2. The double quotes don't allow you to use %PATH% to handle the parentheses problem
  3. And what will a referenced variable like %USERPROFILE% contain?
Portuguese answered 11/8, 2017 at 22:22 Comment(1)
What has this to do with running two commands in one line in Windows CMD?Cyanotype
Q
-3

It's simple: just differentiate them with && signs. Example:

echo "Hello World" && echo "GoodBye World".

"Goodbye World" will be printed after "Hello World".

Quincy answered 5/6, 2017 at 15:6 Comment(4)
Independent of the fact, that there are already old answers that shows the same, it's still not quite correct. && is a conditional operator, the next command is only executed when the first command succeded (errorlevel=0)Parhelion
of course. it's self evident if the person wanna run two commands those two will be correct and thus everything will go goodQuincy
Rajan: he means "the next command is only executed if the first command succeeds".Izanagi
"Goodbye World will be printed after Hello World" provided printing Hello World did not fail. as @Parhelion has said, && is conditional. & runs commands regardless if the previous was successful or not.Crissy

© 2022 - 2024 — McMap. All rights reserved.