Windows cmd несколько команд в одной строке

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?

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?

Soviut's user avatar

Soviut

86.7k47 gold badges187 silver badges254 bronze badges

asked Nov 8, 2011 at 18:31

flybywire's user avatar

flybywireflybywire

255k190 gold badges395 silver badges499 bronze badges

0

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

answered Nov 8, 2011 at 18:33

djdanlib's user avatar

15

A quote from the documentation:

  • Source: Microsoft, Windows XP Professional Product Documentation, Command shell overview
  • Also: An A-Z Index of Windows CMD commands

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.

Jean-François Corbett's user avatar

answered Nov 8, 2011 at 18:36

Raihan's user avatar

RaihanRaihan

9,9655 gold badges27 silver badges45 bronze badges

10

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

Peter Mortensen's user avatar

answered Nov 8, 2011 at 18:37

manojlds's user avatar

manojldsmanojlds

284k62 gold badges466 silver badges415 bronze badges

2

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

answered Nov 12, 2013 at 6:39

TroodoN-Mike's user avatar

TroodoN-MikeTroodoN-Mike

15.5k14 gold badges55 silver badges78 bronze badges

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

answered Nov 8, 2011 at 18:34

scrappedcola's user avatar

scrappedcolascrappedcola

10.3k1 gold badge30 silver badges41 bronze badges

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

set A=Hello & call echo %A%

Stephan's user avatar

Stephan

52.9k10 gold badges57 silver badges90 bronze badges

answered Mar 13, 2016 at 11:06

SSi's user avatar

SSiSSi

3973 silver badges5 bronze badges

5

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:UsersUserNameAppDataLocalTempMyFile5

Graham's user avatar

Graham

7,30118 gold badges58 silver badges84 bronze badges

answered Aug 3, 2016 at 14:31

sambul35's user avatar

sambul35sambul35

1,02814 silver badges22 bronze badges

1

cmd /c ipconfig /all & Output.txt

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

Jeremy Collette's user avatar

answered Apr 16, 2014 at 5:41

dpp.2325's user avatar

dpp.2325dpp.2325

1311 silver badge3 bronze badges

0

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:WindowsMicrosoft.NETFrameworkv4.0.30319regasm.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_ROOTdllfile]
@="Application Extension"

[HKEY_CLASSES_ROOTdllfileShellRegAsm]
@="Register Assembly"

[HKEY_CLASSES_ROOTdllfileShellRegAsmcommand]
@="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.

Community's user avatar

answered Jan 26, 2015 at 20:35

SNAFUBAR's user avatar

SNAFUBARSNAFUBAR

811 silver badge3 bronze badges

1

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

npm install; npm start

answered Feb 22, 2022 at 11:37

Vikas Chauhan's user avatar

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.

Peter Mortensen's user avatar

answered Apr 29, 2017 at 23:16

PyDever's user avatar

PyDeverPyDever

942 silver badges10 bronze badges

3

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!

answered Dec 13, 2016 at 4:41

PryroTech's user avatar

PryroTechPryroTech

5041 gold badge3 silver badges12 bronze badges

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.

Peter Mortensen's user avatar

answered Mar 18, 2017 at 11:16

sdcxp's user avatar

sdcxpsdcxp

411 bronze badge

Use & symbol in windows to use command in one line

C:UsersArshdeep Singh>cd DesktopPROJECTSPYTHONprogramiz & jupyter notebook

like in linux
we use,

touch thisfile ; ls -lstrh

answered May 20, 2020 at 7:01

Arshdeep Kharbanda's user avatar

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 :)

answered Sep 6, 2022 at 21:31

 Tims's user avatar

Tims Tims

4014 silver badges6 bronze badges

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.

Peter Mortensen's user avatar

answered Jul 22, 2016 at 8:56

notarealname's user avatar

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:xampphtdocsproject & gulp & gulp watch

Peter Mortensen's user avatar

answered May 7, 2017 at 14:09

Mile Mijatović's user avatar

Mile MijatovićMile Mijatović

2,7122 gold badges23 silver badges40 bronze badges

Yes there is. It’s &.

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

& will execute regardless.

answered Apr 19, 2019 at 3:29

هادی کشاورز    Hadi Keshavarz's user avatar

0

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.

answered Nov 6, 2020 at 21:03

npocmaka's user avatar

npocmakanpocmaka

54.5k18 gold badges147 silver badges183 bronze badges

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 :

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 =)

answered Nov 25, 2020 at 21:50

Bk01's user avatar

Bk01Bk01

334 bronze badges

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:CompanyCool Tool";%USERPROFILE%AppDataLocalMicrosoftWindowsApps;

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?

answered Aug 11, 2017 at 22:22

V15I0N's user avatar

V15I0NV15I0N

3964 silver badges17 bronze badges

1

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

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

«Goodbye World» will be printed after «Hello World».

answered Jun 5, 2017 at 15:06

Rajan Dhanowa's user avatar

4

В этой небольшой заметке рассмотрим, как выполнить несколько cmd или PowerShell команд в одной строке. Такая задача периодически возникает при вызове команд PowerShell из внешних программ, из планировщика заданий Windows, логон скриптов, когда нужно обойти политику выполнения скриптов PowerShell, или когда нужно быстро передать пользователю кусок кода для выполнения при диагностике/ исправлении проблем на компьютере.

Выполнение нескольких команд в консоли CMD

В cmd для последовательного запуска команд в одной строке используется оператор
&
. Например:

net stop wuauserv & net start wuauserv & wuauclt /detectnow

выполнить несколько последовательных команда в cmd

Если нужно, чтобы вторая команда выполнялась только после успешного выполнения первой, используются формат
&&
:

ipconfig /flushdns && ipconfig /renew

Можно использовать и обратное условие: вторая команда будет выполнена, только если первая вернула ошибку:

net stop wuauserv6 || net start wuauserv

Запуск нескольких команд PowerShell в одной строке

В PowerShell если использовать знак амперсанда для разделения команд в одной строке, появится ошибка:

The ampersand (&) character is not allowed. The & operator is reserved for future use;

Вместо знака & для разделения команд PowerShell в одной строке используется символ точка с запятой (
;
):

restart-service wuauserv -verbose; get-process notepad

запуск нескольких командлетов powershell в одну строку

Эта однострочная PowerShell команда перезапустит службу Windows и после завершения первой команды выведет информацию о процессе.

Популярным примером сокращения команд в PowerShell является конвейеры (pipe/pipeline), которые позволяют передать результаты одной команды следующей по конвейеру. В PowerShell в качестве оператора конвейера используется символ “|”. Например, пример команды с конвейером:

Get-Service -Name wususerv | Stop-Service

Этот же код в полном виде можно записать в несколько строк:

$service = Get-Service -Name wususerv
$serviceName = $service.Name
Stop-Service -Name $serviceName

Получилась неплохая экономия по размеру кода, а код стал даже более простым и читаемым.

Для запуска нескольких команда PowerShell через меню Пуск -> Выполнить, используйте формат:

powershell -command &"{ipconfig /all; tracert yandex.ru; pause "Press any key to continue"}"

Если вы запускаете эти же команды через консоль powershell, используйте синтаксис:

powershell -command {ipconfig /all; tracert yandex.ru; pause "Press any key to continue"}

При запуске нескольких команд PowerShell через планировщик Windows, можно использовать такой формат:

c:windowsSystem32WindowsPowerShellv1.0powershell.exe -Command {Get-EventLog -LogName security; ipconfig /all ; get-service servicename}"

В версии PowerShell Core 7.x доступны новые операторы && и ||. Они работают так, же как в cmd.

Оператор
&&
выполнит команды PowerShell справа от себя, если команда слева выполнена успешно:

Write-host "Hello!" && Write-host "World!"

условные команды в одной строке powershell

Оператор
||
используется, когда нужно выполнить команду, если первая команда вернула ошибку:

get-service servicename || write-host "missing service"

выполнить вторую команду powershell, если первая вернула ошибку

Для того чтобы выполнить несколько команд из одной командной строки, нужно объединить их с помощью символа условной обработки:

  • команда1 & команда2 — Используется для разделения нескольких команд в одной командной строке. В cmd.exe выполняется первая команда, затем вторая команда.

  • команда1 && команда2 — Запускает команду, стоящую за символом &&, только если команда, стоящая перед этим символом была выполнена успешно. В cmd.exe выполняется первая команда. Вторая команда выполняется, только если первая была выполнена успешно.

  • команда1 || команда2 — Запускает команду, стоящую за символом ||, только если команда, стоящая перед символом || не была выполнена. В cmd.exe выполняется первая команда. Вторая команда выполняется, только если первая не была выполнена (полученный код ошибки превышает ноль).

Пример:

attrib -H "file.txt" && ren "file.txt" "file.tmp"

С файла file.txt будет снят атрибут «Скрытый» и если команда attrib при этом не вернёт ошибку, файл будет переименован в file.tmp.

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?

Soviut's user avatar

Soviut

86.7k47 gold badges187 silver badges254 bronze badges

asked Nov 8, 2011 at 18:31

flybywire's user avatar

flybywireflybywire

255k190 gold badges395 silver badges499 bronze badges

0

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

answered Nov 8, 2011 at 18:33

djdanlib's user avatar

15

A quote from the documentation:

  • Source: Microsoft, Windows XP Professional Product Documentation, Command shell overview
  • Also: An A-Z Index of Windows CMD commands

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.

Jean-François Corbett's user avatar

answered Nov 8, 2011 at 18:36

Raihan's user avatar

RaihanRaihan

9,9655 gold badges27 silver badges45 bronze badges

10

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

Peter Mortensen's user avatar

answered Nov 8, 2011 at 18:37

manojlds's user avatar

manojldsmanojlds

284k62 gold badges466 silver badges415 bronze badges

2

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

answered Nov 12, 2013 at 6:39

TroodoN-Mike's user avatar

TroodoN-MikeTroodoN-Mike

15.5k14 gold badges55 silver badges78 bronze badges

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

answered Nov 8, 2011 at 18:34

scrappedcola's user avatar

scrappedcolascrappedcola

10.3k1 gold badge30 silver badges41 bronze badges

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

set A=Hello & call echo %A%

Stephan's user avatar

Stephan

52.9k10 gold badges57 silver badges90 bronze badges

answered Mar 13, 2016 at 11:06

SSi's user avatar

SSiSSi

3973 silver badges5 bronze badges

5

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:UsersUserNameAppDataLocalTempMyFile5

Graham's user avatar

Graham

7,30118 gold badges58 silver badges84 bronze badges

answered Aug 3, 2016 at 14:31

sambul35's user avatar

sambul35sambul35

1,02814 silver badges22 bronze badges

1

cmd /c ipconfig /all & Output.txt

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

Jeremy Collette's user avatar

answered Apr 16, 2014 at 5:41

dpp.2325's user avatar

dpp.2325dpp.2325

1311 silver badge3 bronze badges

0

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:WindowsMicrosoft.NETFrameworkv4.0.30319regasm.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_ROOTdllfile]
@="Application Extension"

[HKEY_CLASSES_ROOTdllfileShellRegAsm]
@="Register Assembly"

[HKEY_CLASSES_ROOTdllfileShellRegAsmcommand]
@="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.

Community's user avatar

answered Jan 26, 2015 at 20:35

SNAFUBAR's user avatar

SNAFUBARSNAFUBAR

811 silver badge3 bronze badges

1

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

npm install; npm start

answered Feb 22, 2022 at 11:37

Vikas Chauhan's user avatar

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.

Peter Mortensen's user avatar

answered Apr 29, 2017 at 23:16

PyDever's user avatar

PyDeverPyDever

942 silver badges10 bronze badges

3

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!

answered Dec 13, 2016 at 4:41

PryroTech's user avatar

PryroTechPryroTech

5041 gold badge3 silver badges12 bronze badges

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.

Peter Mortensen's user avatar

answered Mar 18, 2017 at 11:16

sdcxp's user avatar

sdcxpsdcxp

411 bronze badge

Use & symbol in windows to use command in one line

C:UsersArshdeep Singh>cd DesktopPROJECTSPYTHONprogramiz & jupyter notebook

like in linux
we use,

touch thisfile ; ls -lstrh

answered May 20, 2020 at 7:01

Arshdeep Kharbanda's user avatar

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 :)

answered Sep 6, 2022 at 21:31

 Tims's user avatar

Tims Tims

4014 silver badges6 bronze badges

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.

Peter Mortensen's user avatar

answered Jul 22, 2016 at 8:56

notarealname's user avatar

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:xampphtdocsproject & gulp & gulp watch

Peter Mortensen's user avatar

answered May 7, 2017 at 14:09

Mile Mijatović's user avatar

Mile MijatovićMile Mijatović

2,7122 gold badges23 silver badges40 bronze badges

Yes there is. It’s &.

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

& will execute regardless.

answered Apr 19, 2019 at 3:29

هادی کشاورز    Hadi Keshavarz's user avatar

0

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.

answered Nov 6, 2020 at 21:03

npocmaka's user avatar

npocmakanpocmaka

54.5k18 gold badges147 silver badges183 bronze badges

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 :

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 =)

answered Nov 25, 2020 at 21:50

Bk01's user avatar

Bk01Bk01

334 bronze badges

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:CompanyCool Tool";%USERPROFILE%AppDataLocalMicrosoftWindowsApps;

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?

answered Aug 11, 2017 at 22:22

V15I0N's user avatar

V15I0NV15I0N

3964 silver badges17 bronze badges

1

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

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

«Goodbye World» will be printed after «Hello World».

answered Jun 5, 2017 at 15:06

Rajan Dhanowa's user avatar

4

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?

Soviut's user avatar

Soviut

86.7k47 gold badges187 silver badges254 bronze badges

asked Nov 8, 2011 at 18:31

flybywire's user avatar

flybywireflybywire

255k190 gold badges395 silver badges499 bronze badges

0

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

answered Nov 8, 2011 at 18:33

djdanlib's user avatar

15

A quote from the documentation:

  • Source: Microsoft, Windows XP Professional Product Documentation, Command shell overview
  • Also: An A-Z Index of Windows CMD commands

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.

Jean-François Corbett's user avatar

answered Nov 8, 2011 at 18:36

Raihan's user avatar

RaihanRaihan

9,9655 gold badges27 silver badges45 bronze badges

10

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

Peter Mortensen's user avatar

answered Nov 8, 2011 at 18:37

manojlds's user avatar

manojldsmanojlds

284k62 gold badges466 silver badges415 bronze badges

2

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

answered Nov 12, 2013 at 6:39

TroodoN-Mike's user avatar

TroodoN-MikeTroodoN-Mike

15.5k14 gold badges55 silver badges78 bronze badges

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

answered Nov 8, 2011 at 18:34

scrappedcola's user avatar

scrappedcolascrappedcola

10.3k1 gold badge30 silver badges41 bronze badges

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

set A=Hello & call echo %A%

Stephan's user avatar

Stephan

52.9k10 gold badges57 silver badges90 bronze badges

answered Mar 13, 2016 at 11:06

SSi's user avatar

SSiSSi

3973 silver badges5 bronze badges

5

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:UsersUserNameAppDataLocalTempMyFile5

Graham's user avatar

Graham

7,30118 gold badges58 silver badges84 bronze badges

answered Aug 3, 2016 at 14:31

sambul35's user avatar

sambul35sambul35

1,02814 silver badges22 bronze badges

1

cmd /c ipconfig /all & Output.txt

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

Jeremy Collette's user avatar

answered Apr 16, 2014 at 5:41

dpp.2325's user avatar

dpp.2325dpp.2325

1311 silver badge3 bronze badges

0

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:WindowsMicrosoft.NETFrameworkv4.0.30319regasm.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_ROOTdllfile]
@="Application Extension"

[HKEY_CLASSES_ROOTdllfileShellRegAsm]
@="Register Assembly"

[HKEY_CLASSES_ROOTdllfileShellRegAsmcommand]
@="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.

Community's user avatar

answered Jan 26, 2015 at 20:35

SNAFUBAR's user avatar

SNAFUBARSNAFUBAR

811 silver badge3 bronze badges

1

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

npm install; npm start

answered Feb 22, 2022 at 11:37

Vikas Chauhan's user avatar

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.

Peter Mortensen's user avatar

answered Apr 29, 2017 at 23:16

PyDever's user avatar

PyDeverPyDever

942 silver badges10 bronze badges

3

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!

answered Dec 13, 2016 at 4:41

PryroTech's user avatar

PryroTechPryroTech

5041 gold badge3 silver badges12 bronze badges

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.

Peter Mortensen's user avatar

answered Mar 18, 2017 at 11:16

sdcxp's user avatar

sdcxpsdcxp

411 bronze badge

Use & symbol in windows to use command in one line

C:UsersArshdeep Singh>cd DesktopPROJECTSPYTHONprogramiz & jupyter notebook

like in linux
we use,

touch thisfile ; ls -lstrh

answered May 20, 2020 at 7:01

Arshdeep Kharbanda's user avatar

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 :)

answered Sep 6, 2022 at 21:31

 Tims's user avatar

Tims Tims

4014 silver badges6 bronze badges

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.

Peter Mortensen's user avatar

answered Jul 22, 2016 at 8:56

notarealname's user avatar

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:xampphtdocsproject & gulp & gulp watch

Peter Mortensen's user avatar

answered May 7, 2017 at 14:09

Mile Mijatović's user avatar

Mile MijatovićMile Mijatović

2,7122 gold badges23 silver badges40 bronze badges

Yes there is. It’s &.

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

& will execute regardless.

answered Apr 19, 2019 at 3:29

هادی کشاورز    Hadi Keshavarz's user avatar

0

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.

answered Nov 6, 2020 at 21:03

npocmaka's user avatar

npocmakanpocmaka

54.5k18 gold badges147 silver badges183 bronze badges

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 :

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 =)

answered Nov 25, 2020 at 21:50

Bk01's user avatar

Bk01Bk01

334 bronze badges

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:CompanyCool Tool";%USERPROFILE%AppDataLocalMicrosoftWindowsApps;

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?

answered Aug 11, 2017 at 22:22

V15I0N's user avatar

V15I0NV15I0N

3964 silver badges17 bronze badges

1

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

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

«Goodbye World» will be printed after «Hello World».

answered Jun 5, 2017 at 15:06

Rajan Dhanowa's user avatar

4

Если вы какое-то время использовали Windows 10, возможно, вы знаете о командной строке. Командная строка-одна из лучших утилит Windows 10, которая позволяет автоматизировать и выполнять широкий спектр задач.

Есть много вещей, которые вы можете делать с помощью командной строки. Например, вы можете использовать лучший Команды CMD для выполнения основных задач. Точно так же бывают случаи, когда мы хотим запустить несколько команд в командной строке.

Вы можете выполнять несколько команд в командной строке, но вам нужно делать это вручную. Что, если я скажу вам, что вы можете запускать несколько команд одновременно в командной строке?

Да, вы можете запускать две команды в одной строке в командной строке Windows. Для этого вам нужно создать файл пакетного сценария с помощью Блокнота. Ниже мы поделились двумя лучшими методами для запуска нескольких команд в CMD на компьютерах с Windows 10. Давай проверим.

1. С помощью Блокнота

Этот метод включает создание пакетного сценария для выполнения нескольких команд. Используя это, вы можете автоматически выполнять все свои команды одну за другой. Для этого мы собираемся использовать команды для сброса кеша DNS в Windows 10-

  • ipconfig/displaydns
  • ipconfig/flushdns
  • ipconfig/release
  • ipconfig/обновить

Шаг 1. Прежде всего откройте Блокнот на своем компьютере.

Шаг 2. Теперь введите команды, которые вы хотите выполнить, одним щелчком мыши. В этом примере мы используем четыре команды, упомянутые выше.

Шаг 3. Затем нажмите файл и выберите параметр «Сохранить как» .

Шаг 4. Теперь сохраните этот файл с расширением .bat . Например, DNSreset.bat

Шаг 5. Если вы хотите сбросить кеш DNS, дважды щелкните файл пакетного сценария.

Вот и все! Вы сделали. Вот как вы можете запускать несколько команд в командной строке.

2. Использование специальных символов

В этом методе мы будем использовать некоторые специальные символы между командами, чтобы выполнять их одновременно. Следуйте инструкциям, приведенным ниже.

Шаг 1. Если вы хотите запустить две или более команд одновременно, просто вставьте «&» между командами. Например- ipconfig/flushdns & ipconfig/Renew

.

Шаг 2. Если вы хотите выполнить вторую команду после успешного выполнения первой, используйте «&&» между командами. Например- ipconfig/flushdns && ipconfig/Renew

.

Шаг 3. Если вы хотите запустить вторую команду только в том случае, если первая не была выполнена, введите между командами «||» . Например- ipconfig/flushdns || ipconfig/обновить

Вот и все! Вы сделали. Вы можете использовать эти знаки между командами по своему желанию.

Итак, эта статья посвящена тому, как запускать несколько команд в CMD в Windows 10. Надеюсь, эта статья вам помогла! Пожалуйста, поделитесь им также со своими друзьями. Если у вас есть какие-либо сомнения по этому поводу, сообщите нам об этом в поле для комментариев ниже.


Windows, Windows 10, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP

Как одновременно выполнить несколько команд в командной строке

  • 13.09.2020
  • 4 934
  • 4
  • 22
  • 22
  • 0

Как одновременно выполнить несколько команд в командной строке

  • Содержание статьи
    • Использование символов условной обработки
    • Комментарии к статье ( 4 шт )
    • Добавить комментарий

Для объединения команд в командной строке в одну строку, используются специальные символы, которые называются символами условной обработки. У командного процессора в MS-DOS и интерпретатора командной строки Windows в виде COMMAND.com или CMD.exe их существует в количестве пяти штук, но нас интересует только три из них.

Использование символов условной обработки

Для экранирования описанных ниже символов &, &&, || следует использовать специальный символ ^.

  • Символ: &
    Написание в одну строку: команда 1 & команда 2
    Написание в несколько строк:

    команда 1
    команда 2

    В командной строке можно выполнить две и более команды, написав их в одну строку (команду), и разделив их символом &. Работает это следующим образом: после выполнения первой команды, будет выполнена вторая команда, и т. д. В качестве примера рассмотрим запуск Калькулятора (calc.exe), а затем — Блокнота (notepad.exe):

    calc.exe & notepad.exe
  • Символ: &&
    Написание в одну строку: команда 1 && команда 2
    Написание в несколько строк:

    команда 1
    if %errorlevel% EQU 0 команда 2

    В отличии от предыдущего варианта, при разделении команд с помощью символов &&, команда, следующая после данных символов, будет выполнена только в том случае, если первая команда была завершена без ошибок. Например, попробуем запустить процесс форматирования диска F:, и если оно выполнится успешно — скопируем туда содержимое директории D:Archive. Соответственно, если форматирование завершится с ошибкой, то и вторая команда на копирование не будет работать.

    format F: /Q && copy D:Archive*.* F:
  • Символ: ||
    Написание в одну строку: команда 1 || команда 2
    Написание в несколько строк:

    команда 1
    if %errorlevel% NEQ 0 команда 2

    Полная противоположность предыдущему варианту — вторая команда срабатывает только при условии того, что первая команда не была успешно выполнена. К примеру, попробуем запустить несуществующую программу program.exe, а поскольку такой не существует (т. е. первая команда завершится с ошибкой) — запустим вторую программу в виде Калькулятора (calc.exe):

    program.exe || calc.exe
  • Символ: ( и )
    Написание в одну строку: (команда 1 & команда 2) && команда 3

    В некоторых случаях может понадобится написать более сложные условия выполнения команд в одной строке, где от результата выполнения команды зависят дальнейшие действия. Здесь на помощь придут операторы ( и ), позволяющие группировать команды. К примеру, нужно проверить наличие файла по адресу F:data.txt, и если он есть — открыть его в Блокноте, если же его нет — предварительно скопировать его по адресу D:data.txt и уже после этого открыть в Блокотне.

    dir F:data.txt && (notepad.exe F:data.txt) || (copy D:data.txt F:data.txt & notepad.exe F:data.txt)

    В прочем ничто не мешает изменить условия, заменив операторы, и подстроив команды под нужный Вам сценарий.

Содержание

  1. Как запустить две команды в одной строке в Windows CMD?
  2. 16 ответов
  3. Как запустить две команды в одной строке в Windows CMD?
  4. 21 ответ
  5. Как выполнить две команды в одной строке в Windows CMD?
  6. 16 ответов:
  7. cmd несколько команд в одной строке
  8. Комментарии
  9. Выполнение команд последовательно
  10. Зависимое выполнение команд
  11. 7 ответов
  12. Выполнить несколько команд с 1 строкой в ​​командной строке Windows?

Как запустить две команды в одной строке в Windows CMD?

Я хочу запустить две команды в консоли Windows CMD.

в Linux я бы сделал это так

Как это делается в Windows?

16 ответов

как это на всех ОС Microsoft с 2000 года, и все еще хорошо сегодня:

если вы хотите, чтобы вторая команда выполнялась только в том случае, если первая вышла успешно:

синтаксис одного амперсанда ( & ) для выполнения нескольких команд в одной строке восходит к Windows XP, Windows 2000 и некоторым более ранним версиям NT. (4.0 по крайней мере, согласно одному комментатору здесь.)

есть немало других точек об этом вы найдете внизу эта страница.

исторические данные для тех, кто может найти его образования.

до этого синтаксис && был только функцией замены оболочки 4DOS до того, как эта функция была добавлена в интерпретатор команд Microsoft.

В Windows 95, 98 и меня, вы бы использовать символ трубы вместо:

в MS-DOS 5.0 и более поздних версиях интерпретатора команд Windows и NT разделитель команд (недокументированный был символ 20 (Ctrl+T), который я буду представлять с ^T здесь.

цитата из документации:

использование нескольких команд и символов условной обработки

можно выполнять несколько команд из одной командной строки или сценария с помощью сиволов условной обработки. При выполнении нескольких команд с условным обработка символов команды справа от условного символа обработки действуют на основе результатов команды слева от условного символа обработки.

например, может потребоваться выполнить команду только в случае сбоя предыдущей команды. Или может потребоваться выполнить команду только в том случае, если предыдущая команда выполнена успешно.

для передачи нескольких команд можно использовать специальные символы, перечисленные в следующей таблице.

& [. ]
command1 & command2
Используется для разделения нескольких команд в одной командной строке. УМК.exe запускает первую команду, а затем вторую команду.

&& [. ]
command1 && command2
Использовать для выполнения команды&&, только если команда, стоящая перед символом успеха. УМК.exe запускает первую команду, а затем запускает вторую команду, только если первая команда выполнена успешно.

|| [. ]
command1 || command2
Используйте для выполнения следующей команды / / только в том случае, если предыдущая команда || не выполняется. УМК.exe запускает первую команду, а затем запускает вторую команду, только если первая команда не завершена успешно (получает код ошибки больше нуля).

( ) [. ]
(command1 & command2)
Используется для группировки или вложения команд.

Источник

Как запустить две команды в одной строке в Windows CMD?

Я хочу запустить две команды в консоли Windows CMD.

В Linux я бы сделал это так

Как это делается в Windows?

21 ответ

Подобно этому во всех операционных системах Microsoft с 2000 года и по сей день:

Если вы хотите, чтобы вторая команда выполнялась только в случае успешного завершения первой команды:

Синтаксис с одним амперсандом (&) для выполнения нескольких команд в одной строке восходит к Windows XP, Windows 2000 и некоторым более ранним версиям NT. (По крайней мере, 4.0, по словам одного из комментаторов.)

Есть еще немало других моментов, которые вы найдете, прокручивая эту страницу вниз.

Ниже приводятся исторические данные для тех, кто может счесть это познавательным.

До этого синтаксис && был только функцией замены оболочки 4DOS до того, как эта функция была добавлена ​​в командный интерпретатор Microsoft.

В Windows 95, 98 и ME вместо этого следует использовать вертикальную черту:

В MS-DOS 5.0 и более поздних версиях, в некоторых более ранних версиях интерпретатора команд для Windows и NT, (недокументированным) разделителем команд был символ 20 (Ctrl + T), который я обозначу здесь как ^ T.

Просто добавьте && между ними. Например: Cls && echo ‘hello’ && dir c:

«Goodbye World» будет напечатан после «Hello World».

Когда вы пытаетесь использовать или манипулировать переменными в одной строке, остерегайтесь их содержимого! Например. переменная, подобная следующей

Может привести к множеству неуправляемых проблем, если вы будете использовать его как %PATH%

Будет создан пустой файл.

В cmd вы получите что-то вроде этого:

mM2dS

Но, как упоминалось ранее другими, действительно рекомендуется использовать оператор & для выполнения нескольких командных строк в одной строке из командной строки CMD.

Используйте символ & в окнах, чтобы использовать команду в одной строке

Как в Linux, который мы используем,

&& выполнит команду 2 по завершении команды 1, если она не завершилась ошибкой.

& будет выполняться независимо.

Еще один пример: например, когда мы используем систему сборки gulp вместо

Мы можем сделать это одной строкой:

Трубопровод имеет некоторую проблему, но она не критична, если люди знают, как она работает.

В Windows 10 вы также можете использовать скриптраннер:

Он позволяет вам запускать несколько команд в одной строке, которую вы хотите, вы можете запускать их последовательно или без ожидания друг друга, вы можете установить тайм-ауты и откат при ошибке.

Я пытаюсь получить два эхо-запроса в одном окне, и это последовательная команда в одной строке. После завершения первого запустите вторую команду.

Решением было объединить с start /b в командной строке Windows 7.

Команда, используемая для запуска в той же строке:

В любом случае, если вы хотите проанализировать вывод, я не рекомендую это использовать. Я заметил, что вывод скремблируется между выводом команд.

Чтобы выполнить две команды одновременно, вы должны поставить символ & (амперсанд) между двумя командами. Вот так:

Что ж, у вас есть два варианта: трубопровод или просто & :

Конвейер ( | ) больше предназначен для передачи вывода одной команды в другую. И ( & ) просто говорит: беги то и это.

cmd /k C:WindowsMicrosoft.NETFrameworkv4.0.30319regasm.exe «%1″ /codebase »%1» & pause & exit

Теперь у меня есть красивое контекстное меню для регистрации сборки.

cmd /c ipconfig /all & Output.txt

Эта команда выполняет команду и открывает файл Output.txt одной командой

При выполнении нескольких команд в одной строке можно использовать ряд символов обработки, которые могут привести к перенаправлению обработки в некоторых случаях, изменению вывода в другом случае или просто к сбою. Одним из важных случаев является размещение в одной строке команд, управляющих переменными.

Как вы видите в приведенном выше примере, когда команды, использующие переменные, помещаются в одну строку, вы должны использовать отложенное раскрытие для обновления значений переменных. Если ваша переменная проиндексирована, используйте команду CALL с модификаторами %%, чтобы обновить ее значение в той же строке:

Если вы хотите создать ярлык cmd (например, на рабочем столе), добавьте параметр / k (/ k означает сохранить, / c закроет окно):

Вы можете использовать &, чтобы запускать команды одну за другой. Пример: c:dir & vim myFile.txt

Цитата из документации:

Использование нескольких команд и условной обработки символов

Вы можете запускать несколько команд из одной командной строки или сценария, используя символы условной обработки. Когда вы запускаете несколько команд с символами условной обработки, команды справа от символа условной обработки действуют на основе результатов команды слева от символа условной обработки.

Например, вы можете захотеть запустить команду только в случае сбоя предыдущей команды. Или вы можете захотеть запустить команду, только если предыдущая команда выполнена успешно.

Вы можете использовать специальные символы, перечисленные в следующей таблице, для передачи нескольких команд.

& [. ]
command1 & command2
Используется для разделения нескольких команд в одной командной строке. Cmd.exe выполняет первую команду, а затем вторую.

&& [. ]
command1 && command2
Используйте для запуска команды, следующей за &&, только если команда, предшествующая символу, выполнена успешно. Cmd.exe запускает первую команду, а затем выполняет вторую команду, только если первая команда завершилась успешно.

|| [. ]
command1 || command2
Используйте для выполнения следующей команды || только если команда, предшествующая || терпит неудачу. Cmd.exe запускает первую команду, а затем выполняет вторую команду только в том случае, если первая команда не завершилась успешно (получает код ошибки больше нуля).

( ) [. ]
(command1 & command2)
Используется для группировки или вложения нескольких команд.

Источник

Как выполнить две команды в одной строке в Windows CMD?

Я хочу запустить две команды в консоли CMD Windows.

в Linux я бы сделал это так

Как это делается на Windows?

16 ответов:

как это на всех ОС Microsoft с 2000 года, и до сих пор хорошо сегодня:

если вы хотите, чтобы вторая команда выполнялась только при успешном завершении первой:

синтаксис single ampersand ( & ) для выполнения нескольких команд в одной строке восходит к Windows XP, Windows 2000 и некоторым более ранним версиям NT. (4.0 по крайней мере, согласно одному комментатору здесь.)

есть довольно много других моментов об этом, что вы найдете прокрутку вниз эта страница.

исторические данные для тех, кто может найти его образования.

до этого синтаксис && был только функцией замены оболочки 4DOS, прежде чем эта функция была добавлена в интерпретатор команд Microsoft.

В Windows 95, 98 и мне, вы бы использовать символ трубы вместо:

в MS-DOS 5.0 и более поздних версиях, через некоторые более ранние версии Windows и NT интерпретатора команд, (недокументированный) разделитель команд был символ 20 (Ctrl+T), который я буду представлять с ^T здесь.

использование нескольких команд и символов условной обработки

можно выполнять несколько команд из одной командной строки или сценария с помощью сиволов условной обработки. При выполнении нескольких команд с условным символы обработки, выполнение команд, стоящих справа от условного действовать символьной обработки в зависимости от результатов выполнения команды, стоящей слева от символа условной обработки.

например, вы можете выполнить команду только в том случае, если предыдущая команда завершилась неудачно. Или вы можете выполнить команду только в том случае, если предыдущая команда выполнена успешно.

для передачи нескольких команд можно использовать специальные символы, перечисленные в следующей таблице.

& [. ]
command1 & command2
Используется для разделения нескольких команд в одной командной строке. УМК.exe запускает первую команду, а затем вторую команду.

&& [. ]
command1 && command2
Использовать для выполнения команды&&, только если команда, стоящая перед символом успеха. УМК.exe запускает первую команду, а затем запускает вторую команду, только если первая команда выполнена успешно.

|| [. ]
command1 || command2
Используется для выполнения следующей команды | / только в том случае, если предыдущая команда || завершается неудачно. УМК.exe запускает первую команду, а затем запускает вторую команду, только если первая команда не была выполнена успешно (получает код ошибки больше нуля).

( ) [. ]
(command1 & command2)
Используется для группировки или вложения команд.

Источник

cmd несколько команд в одной строке

Для того чтобы выполнить несколько команд из одной командной строки, нужно объединить их с помощью символа условной обработки:

команда1 & команда2 — Используется для разделения нескольких команд в одной командной строке. В cmd.exe выполняется первая команда, затем вторая команда.

команда1 && команда2 — Запускает команду, стоящую за символом &&, только если команда, стоящая перед этим символом была выполнена успешно. В cmd.exe выполняется первая команда. Вторая команда выполняется, только если первая была выполнена успешно.

команда1 || команда2 — Запускает команду, стоящую за символом ||, только если команда, стоящая перед символом || не была выполнена. В cmd.exe выполняется первая команда. Вторая команда выполняется, только если первая не была выполнена (полученный код ошибки превышает ноль).

Пример:

С файла file.txt будет снят атрибут «Скрытый» и если команда attrib при этом не вернёт ошибку, файл будет переименован в file.tmp.

Комментарии rss

225d94d1d9875cf3a353fdb9bbd4272a

Большое спасибо за статью! Именно то, что мне было нужно.

225d94d1d9875cf3a353fdb9bbd4272a

Офигеть! Полезные советы! Спасибо!

225d94d1d9875cf3a353fdb9bbd4272a

Спасибо большое. Давно искал.

2852a5b324d33d53d64357ec0789e3a7

Крутяк, добавлю в закладки.

9a78306c410f1ab32a29fbed504da798

пфффффффффффф вот это лайфхак епт, я тут тыркаю по 6 команд в гите поштучно, а тут вон оно че Михалыч. спасибо большое!

225d94d1d9875cf3a353fdb9bbd4272a

одна вертикальная черта | используется когда нужно выполнить одновременно несколько команд, не зависимо от результата и завершения предыдущей команды

225d94d1d9875cf3a353fdb9bbd4272a

Одна вертикальная черта | перенаправляет вывод предыдущей команды следующей. Например type «file1.txt» | find »string1″ ищет в файле строку содержащую «string1» и выводит ее. Этот вывод можно отправить через | на следующую команду. Или, используя пример: (type «file1.txt» | find »string1″ >nul) && (команды если строка найдена) || (команды если строка не найдена)

225d94d1d9875cf3a353fdb9bbd4272a

При одной вертикальной линии команды выполняются всё равно последовательно.

В командной строке можно объединять сразу несколько команд в одну строку (в один запуск). Например, вам нужно выполнить сначала одну команду, за ней вторую и так далее. Но вы хотите сразу вбить в командной строке одну инструкцию, которая все сделает.

Выполнение команд последовательно

Например, мы хотим выполнить сначала одну команду. Затем, когда она отработает (вернет управление в командную строку), нам нужно запустить вторую команду. Для этого служит символ «;». Таким образом, если набрать в терминале:

Зависимое выполнение команд

то это означает, что команда command2 будет выполнена только в том случае, если команда command1 была выполнена успешно (вернула нулевой код завершения). Каждая следующая команда выполняется только при успешном выполнении предыдущей.

то команда command2 будет выполнена только в том случает, если command1 вернула ошибку (не нулевой код завершения). Каждая следующая команда запускается только если предыдущая вернула ошибку.

Такое поведение объясняется очень просто: интерпретируя И нет смысла выполнять вторую команду, если первая вернула ошибку. А интерпретируя ИЛИ нет смысла выполнять вторую команду если первая выполнилась с успехом.

Этот же результат будет получен в результате выполнения кода:

Операторы && и || можно объединять в одной командной строке:

Эти операторы часто используются в условиях if :

Еще одни пример использования:

Как выполнить несколько команд в командной строке Windows только с одной строкой?

Это не работает. Есть ли символ или разделитель типа ‘;’ выполнить что-то подобное?

7 ответов

&& выполнит команду 2, когда команда 1 будет завершена, если она не сработает.

& будет выполняться независимо.

Затем вам нужно сделать это за 2 шага (однострочное решение находится в конце этого ответа).

Сначала напишите команды во временный пакетный файл (в этом случае вы можете использовать & или && ):

Затем используйте start для запуска командного файла:

start «» «temporary foobar.cmd»

if you leave out the empty pair of double quote marks like this:

start «temporary foobar.cmd»

Вы можете поместить все это вместе на одну строку и даже удалить (удалить) временный пакетный файл ( foobar.cmd ):

Источник

Выполнить несколько команд с 1 строкой в ​​командной строке Windows?

Как я могу выполнить несколько команд в командной строке Windows с помощью одной строки?

Это не работает, очевидно. Есть ли символ или разделитель типа ‘;’ выполнить что-то подобное?

&& выполнит команду 2, когда команда 1 будет выполнена, при условии, что она не завершилась неудачей.

& будет выполнять независимо.

По крайней мере, в MS-DOS 6.22 я использовал клавишу Ctrl +, T чтобы получить символ абзаца. Это сработало так же, как & упомянуто Фоши. Однако это будет работать, только если у вас запущен doskey.exe.

Затем вам нужно сделать это в 2 шага (однострочное решение находится в конце этого ответа).

Сначала запишите команды во временный пакетный файл (в этом случае вы можете использовать & или && ):

Обратите внимание, что вам нужно «экранировать» каждый из «&»s (амперсандов) с помощью, «^» чтобы их можно было рассматривать как обычные символы в echo команде. Кроме того, вы можете создать временный пакетный файл с помощью текстового редактора, такого как Блокнот.

Затем используйте start для запуска командного файла:

start «» «temporary foobar.cmd»

если вы пропустите пустую пару двойных кавычек, как это:

start «temporary foobar.cmd»

Если вы хотите start дождаться завершения пакетного файла (после pause закрытия), прежде чем start завершить, то вам нужно добавить /w переключатель в start команду:

Вы можете поместить все это в одну строку и даже удалить (удалить) временный командный файл ( foobar.cmd ):

Обратите внимание, что если вы собираетесь удалить временный пакетный файл, вам необходимо запустить его start с помощью /w переключателя, в противном случае временный пакетный файл, вероятно, будет удален, прежде чем он сможет запустить.

Источник

Понравилась статья? Поделить с друзьями:
  • Windows cannot connect to the printer no printers were found
  • Windows cmd show files in directory
  • Windows cannot connect to the printer access is denied
  • Windows cannot connect to the printer 0x0000011b
  • Windows cannot connect to the printer 0x00000002