I keep seeing commands joined with either && or a semicolon. What changes besides putting two commands on one line?
When should I use && instead of a semicolon in the shell?
Answers
A semicolon runs the next command either way. With &&, the next command runs only if the command before it exits successfully, meaning it returns status 0.
So use a semicolon when the second command should happen regardless. Use && when it depends on the first one working, like changing directories and then running something there.
Reply to this answer
Think of && as โif the previous command succeeded, continue.โ For example, build && run means the run step is skipped if the build fails. With build ; run, the run step happens even after a failed build.
One small detail: the status of a chained command can matter too. If the first command in an && chain fails, the later commands are skipped and the chain has a failure status.
Reply to this answer
There is also ||, which goes the other way: it runs the next command when the previous one fails. A common pattern is command || print-an-error, though for more complicated logic an if statement can be clearer.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions