Skip navigation

Learning How to Chain Commands

I've been experimenting with using the command line, and I wonder if you could recommend an easy way to run a certain command depending on whether another command succeeds or fails?
Three methods exist for running commands together at the command prompt, a procedure known as chaining commands. The simplest method is to use a single ampersand (&) symbol, which simply runs multiple commands consecutively. For example,

command1 & command2 

Command1 runs first, followed by command2, regardless of the success of command1. For example, running

dir & echo %time% 

will list a folder, then write the current time. You aren't limited to two commands; you can keep adding commands, with each command separated by an ampersand. If you require a second command to run only if the first command succeeds, you can use two ampersand (&&) characters. For example, if you run Setx with an invalid argument, the second command won't run:

C:\>setx /goobledegook && echo worked ERROR: Invalid syntax. 

Whereas when I use a valid command, the second command runs and produces the following output:

C:\>setx var2 work && echo worked
  SUCCESS: Specified value was saved. worked 

You can use a double pipe || to run a command only if the previous command fails, as this example shows:

C:\>setx /goobledegook || echo not working
  ERROR: Invalid syntax. not working
—John Savil
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish