9

I have a long Bash command. This command looks something like this:

grunt build && mv file1.txt ../../results && mv file2.txt ../../logs && mv file3.txt ../home && mv file4.txt ../../../deployments

I'm adding this command to a README.md file. I would like to make this a) easy-to-read and b) copy-and-pastable. My question is, how do I make an easy-to-read multi-command line for Bash?

I've tried the following, which did not work:

grunt build && \
  mv file1.txt ../../results && \ 
  mv file2.txt ../../logs && \ 
  mv file3.txt ../home && \
  mv file4.txt ../../../deployments

Thank you.

1 Answer 1

18

Explanation

You can continue a command in the next line with backslash (\), but only if the backslash is immediately before the newline character terminating the line. In your code there are spaces after few backslashes. Remove them.

Note && at the end of the line is enough for Bash to continue reading the command from the next line, even if there are unquoted, unescaped spaces after &&. But not if there is an escaped space, like in your case.


Examples

This will work:

true   && \
echo b   # ^ no space here, newline character immediately after \

And this will work:

true   &&         
echo b # ^^^^^^^^^ zero or more spaces, they don't matter

(Change true to false to learn && really does its job.)

But this won't work*:

true   && \ 
echo b   # ^ escaped space here, it breaks things

The escaped space is like a quoted space. This also won't work*:

true   && ' '
echo b   # ^ quoted space here, it breaks things

* Well, it will work if there's a command named (literal space) in your OS. This is technically possible, yet very, very uncommon (if I saw such executable, I would smell something fishy right away). Still the snippet won't work the way you want it to work because && will connect true and , not true and echo.


Side note

Code like this:

foo && \
bar

(where \ properly escapes the newline) is valid, yet redundant. It can be:

foo &&
bar

Some users don't like any of the above because by inspecting the beginnings of the lines one cannot tell if bar should run conditionally or unconditionally. One needs to inspect the end of the first line (that may be quite long) to find the &&.

Therefore one may prefer this:

foo \
&& bar

Here \ is mandatory, but it's evident bar should depend on the previous line, even if the previous line is very long and one doesn't spot the backslash immediately.

0

You must log in to answer this question.

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