Ubuntu – Difference between | and ||

bashcommand line

What is the difference between | and || ?

When I run this command :

ls -la | id

I get the result of id

When I run this command
:

ls -la || id

I get the result of ls -la

So what is the difference between them ?

Best Answer

| is the pipe operator, which passes the output of the first command to the one that follows.

from man bash:

A pipeline is a sequence of one or more commands separated by the character |. The format for a pipeline is:

[time [-p]] [ ! ] command [ | command2 ... ]

The standard output of command is connected via a pipe to the standard input of command2.

In the example you provide, id doesn't seem to do anything with the output of ls so it just returns the same output as running id alone.


|| is the logical OR operator, and specifies what to do if the first command returns false or fails (is non-zero).

from man bash:

The control operators && and || denote AND lists and OR lists, respectively. An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

In your example, ls -la runs successfully so the id command isn't run. If you did the following:

ls -z || id

and try to pass an invalid option z to ls, then it fails and the id command gets run.