13

I have a makefile where I'm stopping a service before removing a file. When it couldn't stop the service, it would break on error. This is clearly unwanted so I thought I'd add || true but missed a |. Making it:

stop service foo | true
rm /etc/init/foo.conf

I'm confused as to why this is working and what is happening. Does this mean that true is an application and not merely a keyword? Are they the same? Is there a good reason to use | true?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Kit Sunde
  • 4,394
  • 10
  • 30
  • 34
  • The commands make little sense as the exit code of `true` is being ignored. The only side-effect is that `stdout` is redirected to nowhere in an unreliable way. – U. Windl Aug 28 '23 at 21:21

1 Answers1

17

true and false are coreutils (also typically shell built-ins) that just return 0 and non-0, for situations where you happen to need that behavior. From the man pages:

true - do nothing, successfully
false - do nothing, unsuccessfully

So you're piping the output from stop service foo into true, which ignores it and returns 0. Technically it works, but you should probably use || true so it's obvious what your intention was; there's really no reason to pipe output into a program that's not using it

Michael Mrozek
  • 91,316
  • 38
  • 238
  • 232
  • 5
    Makes perfect sense. :) I don't know why but reading *"do nothing, unsuccessfully."* makes me laugh. – Kit Sunde Apr 24 '11 at 20:23
  • 9
    Another reason to avoid `| true` is that if the command produced enough output to fill up the pipe buffer, it would block waiting for `true` to read it. – cjm Apr 24 '11 at 20:53
  • 3
    @cjm or die due to SIGPIPE – Andy Apr 25 '11 at 04:43
  • 6
    @Kit: Note that `foo || true` and `foo | true` won't do the same thing: `foo || true` will show the output from `foo`, whereas `foo | true` will discard everything `foo` writes to its standard output (and `foo` is likely to die with `SIGPIPE` or block, as already indicated). – Gilles 'SO- stop being evil' Apr 25 '11 at 22:06
  • 2
    This answer is perfect except for the word "probably"...! – Sam Watkins Dec 16 '16 at 11:54