Batch file conditional execution using & – && – || – great for one liners

By using the & symbol you can execute a second command after the first command.

as an example, let’s try the following from command prompt.

echo hello

which outputs hello of course

now let’s try the same again but with the addition of &

echo hello & echo goodbye

This now outputs hello, and then outputs goodbye as well

You can achieve the same result but with the caveat that the second command should only run if the first command was successful, this could be extremely important for lots of reasons and could alter the whole dynamic of your script.

Lets use ping to show this example

ping localhost & echo Yes, ping got a reply!

This pings localhost which should always be available and then outputs our text

Now to try with &&

ping localhost && echo Yes, ping got a reply!

This does the same

So let’s try to ping an address that is not reachable and check the results

ping 0.0.0.0 & echo Yes, ping got a reply!

This runs ping which fails but goes ahead and runs our second command regardless, although it has done what we have instructed the visible results are not really accurate and could affect our script / results.

Now let’s try it again using &&

ping localhost && echo Yes, ping got a reply!

This time ping is run but as it is not successful the second command is not executed.

This brings us on the third condition || this only executes text if the command was unsuccessful

So, let’s try this

ping localhost || echo No, ping did not get a reply!

Ping runs successfully and therefore does not execute the second command

And again but this time to an address that will fail

ping 0.0.0.0 || echo No, ping did not get a reply!

as expected, ping is unsuccessful so the second command gets executed

Now, lets put && and || together to cover both eventualities!

ping localhost && echo Yes, ping got a reply! || echo No, ping did not get a reply!

Ping executes successfully and then runs the second command, the third option || is not executed

Now, lets ping the address we now will fail

ping 0.0.0.0 && echo Yes, ping got a reply! || echo No, ping did not get a reply!

This time ping has returned unsuccessful so the second command && is not executed but the third command || is

Print Friendly, PDF & Email

More Like This


Categories


Windows

Tags


  • Post a comment