The Difference Between “&&” and “|” Unix or Linux Command Line
Ever wonder while using the command-line how to run more than one command on a single line?
|
and
&&
These operators allow you to run more than one command on a single line! You may think they are the same, I did for awhile, here is a short tutorial and explanation to each command.
Earlier this week I was working on this site and using Git and Capistrano to deploy the theme from the local to the production server I have to run several commands on the command-line to deploy the changes to the production directory. Since I first started using the command-line on my mac or linux boxes I have always used the
|
to concatenate commands together. I most commonly concatenate commands together such as
cd /some/directory | ls -a
or when I am trying to “quicklook” at a file:
cat somefile.txt | less
I found out when I run the commands
git push origin master | cap deploy
If anytime the push to the git remote repository fails, Capistrano will still run and at least at home (Surry, ME) it can take a while for the terminal to respond.
In short what the
|
does is it tells the computer to run both commands regardless if the first fails or passes. For deploying and committing this does not work, because I need the commands to run in order and tell me if there is an error. So remembering back to this past Christmas while I was at home and compiling a LAMP (Linux Apache MySQL PHP) server I remembered the operator:
&&
This command tells the command-line to run the first command and then if the first command completes successfully then run the second command. For what I need it for it works beautifully because if there is an issue with pushing then Capistrano will not run. The command would look something like this:
git push origin master && cap deploy
I hope you enjoyed this tutorial on the Unix and Linux command-line. Let me know what your thoughts and questions are!