Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have seen this construct in scripts a lot and used it myself, but it bothers me that I can't seem to find it in the documentation.

Example:

[ -f file1 ] &&
[ -f file2 ] &&
echo "Both files exist." ||
echo "One or the other file doesn't exist."

This could also be done with backslashes before the newlines, as mentioned in man bash:

If a \<newline> pair appears,  and  the  backslash  is  not
itself  quoted,  the \<newline> is treated as a line continuation (that
is, it is removed from the input stream and effectively ignored).

Example:

[ -f file1 ] && \
[ -f file2 ] && \
echo "Both files exist." || \
echo "One or the other file doesn't exist."

...but this doesn't seem to be necessary. The first version above works even without the backslashes.

Where can I find this in man bash? (Also, is this bash specific or POSIX compliant?)

share|improve this question
up vote 24 down vote accepted

A newline is ignored in a few contexts where there is manifestly an unterminated command. These contexts include after a control operator (&&, ||, |, &, ;, ;;, but not !).

I don't see this documented in the bash manual.

In POSIX, it's specified via the grammar rules. Wherever the rules have linebreak, you can have zero or more line breaks.

share|improve this answer
    
+1, I didn't knew it worked for the simple pipe ( | ) . I wish we could also put them on the next line, for readability, but it doesn't work that way (if doing that, you need to espace the preceding newline). – Olivier Dulac Jan 6 at 12:49
1  
@OlivierDulac How could that possibly work? When it's processing the current command line, how is it supposed to know that you're planning to type | at the beginning of the next line? Remember, the shell is also used interactively, not just in scripts, and the grammar is the same. – Barmar Jan 6 at 19:43
    
@Barmar : I know, I do know this (wrote compilers at school ^^)... I said "I wish", and it is not a very plausible wish – Olivier Dulac Jan 6 at 19:54
1  
@DocSalvager, can you give an example of a logic bug that would help prevent? I have a hard time seeing it.... – Wildcard Jan 9 at 5:34
2  
@DocSalvager, I wouldn't actually use the code as I wrote it—it was an illustration. Without the last line (the else clause) I would use it that way, though. (For "if this and this then do that" this && this2 && that is fine but for an else clause I'd use an actual if then else fi.) – Wildcard Jan 13 at 4:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.