Combining DOS commands just like you do on UNIX

UNIX/Linux command line is such an interesting thing to play with. Unix Command line users have always been able to combine (more correctly called - chain or pipeline) commands. But did you know this was also possible in the DOS command line?

On UNIX/ Linux you can chain multiple commands by doing something like this:

ls -l | grep " Jan " | cut -c55-100 | sort

Using a Pipe lets you funnel the output of the first command to be used as input by the next command.
Another way of combining commands is using && (that’s a double ampersand symbol) as follows
mkdir backup && cp /some_folder/*.doc ./backup

The second method is different from the first because
  1. There’s no funnelling of output of the first command to the input of the next one
  2. The double-ampersand acts as an AND logical operator. The above example will execute the second command only if the first one succeeds. This does not happen in piping.
The second point is quite important because this means that while the input/output is not funnelled between commands, the success/failure is! The success/failure is determined by a command’s exit status. Here’s a better example (source) to illustrate this point

[ -f unixfile ] && rm unixfile || print "file not found or is irregular"
is better expressed (and read) as the script below
if [ -f unixfile ]
  rm unixfile
  print "file not found or is irregular"

Astute readers would have noted the use of a double pipe (||)  which is entirely different from how it was used in pipelining. As a matter of fact it will do exactly the opposite of the double ampersand. For example,

ping || print “Can’t ping Google”

I am hoping you get the point. But if you are simply looking for a way to execute multiple commands without piping or “double-amp/pipe-ing” (got a better term for this – tell me!), here’s how

rm *.tmp ; cd /home/my_dir ; clear

You got it! Simply put a semicolon between them. Wondering how to do this in Windows/DOS? Here’s how

mkdir dir1 & cd dir1 & copy h:\*.doc .

Yes, put a ampersand between them. As usual, any corrections or better ideas are always welcome. Leave me a comment below.

See also: UNIX Interview questions