0

I found this line in one of our repositories without any comments explaining what it does. I am fixing a bug that I found in this repository and don't know what to make of this line. I am unsure of how to research for this in a time efficient manner, so I'm asking here.

[ "$foo_user" = 'foo' ] && foo_user='bar' || true

It looks like an if statement that tests if $foo_user='foo' then return true, and then sets foo_user to "bar" if it is not set? I really have no idea what to make of this.

What does this code do?

1 Answer 1

3

Let’s split it up:

[ "$foo_user" = 'foo' ]

checks whether the foo_user variable’s value is “foo”.

&& foo_user='bar'

runs if the previous command succeeded (&&); thus if foo_user’s value is “foo”, it is set to “bar” instead.

|| true

runs if the previous command failed (||); thus, in all cases, the compound command (in this case, the complete line) succeeds. This pattern is commonly seen when set -e is enabled (even though it isn’t actually necessary).

See also What are the shell's control and redirection operators?, Precedence of the shell logical operators &&, ||, and Why is pattern "command || true" useful?

2
  • In this case, a set -e would not matter as this is and/or list. However, it would matter in a Makefile, for example, or in any other setting where the exit status of individual pipelines/commands matter.
    – Kusalananda
    May 7, 2021 at 15:22
  • Good point, because the exit code is checked. However it is still commonly seen because many shell developers think that || true is necessary in such circumstances ;-). May 7, 2021 at 15:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .