Data Science Certification Course (AI/ML + DL + Big Data + Python) by E&ICT, IIT Roorkee for $179 | Expires in

 Enroll Now

Linux Basics

69 / 87

Chaining Unix Commands

Say, you want to execute a command only if another command is successful then you use &&.

And if you want a command to be executed if another command has failed, you use ||.

  1. Create a file tea_ready:

    touch tea_ready
  2. The following command would print "Tea is ready" if tea_ready file exists:

    ls -l tea_ready && echo "Tea is ready"
  3. Delete the file tea_ready:

    rm tea_ready
  4. Check the command from #2 again:

    ls -l tea_ready && echo "Tea is ready"
  5. The following will print "Tea is not ready":

    ls -l tea_ready || echo "Tea is not ready"
  6. You can use brackets to avoid confusion:

    (ls -l tea_ready && echo "Tea is ready") || echo "Tea is not ready"