7

I have a very long bash command inside a command substitution like following:

$( comaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaand )

I want to know if there is a way to break this command into shorter lines for the sake of readability like following:

$( com 
   aaaaaaaaaaaaaa
   aaaaaaaaaaaaaa
   nd )
Vombat
  • 12,654
  • 13
  • 44
  • 58

2 Answers2

16

You can mask the newline with \.

$( com\
aaaaaaaaaaaaaa\
aaaaaaaaaaaaaa\
nd )

The \ tells the shell to ignore the newline.

Raphael Ahrens
  • 9,701
  • 5
  • 37
  • 52
  • 2
    The ``\`` part is correct, but you can not indent the subsequent lines. (At least not in the middle of words as in the example.) – manatwork Jul 08 '13 at 08:46
  • yeah copy and paste is a curse! :) – Raphael Ahrens Jul 08 '13 at 08:48
  • I checked it and it works even having indentations! – Vombat Jul 08 '13 at 08:54
  • 2
    @Coffe_Mug It works only if `commaaaaaaaaaaaaaand` is actually `command with a lot of options and | maybe pipes etc`. Otherwise it doesn't work with indentation.Try `echo $(ec\ho a)`, works while `echo $(ec\ho a)` produce *ec: command not found*. While `echo $(echo Hello,\ World)`[note the space after newline] and `echo $(echo Hello, World)` do exactly the same things. – Bakuriu Jul 08 '13 at 13:28
  • @Bakuriu : to be fair, your last example it does exactly the same thing because you forgot to surround the echo parameters with " (as in : `echo "$(echo "Hello,\ World")"` ) so the outer echo receives several parameters and separate them with only 1 default separator. – Olivier Dulac Jul 09 '13 at 09:14
  • @OlivierDulac **That's exactly the point I wanted to make!** Using a single space or multiple spaces to separate options/different commands doesn't make a difference, hence the indentation after the newline doesn't have any effect. If you put the line break inside *one* command(or option) than indentation *does* matter. – Bakuriu Jul 09 '13 at 09:22
  • @Bakuriu: ok ^^ But I wanted to precise, as it could also be read as "`\something` is equivalent to `\something`", which is false in general and only true when the newline and indentation are just (unnacounted for) separators. – Olivier Dulac Jul 09 '13 at 13:23
11

If there are pipe | symbols in a long Bash command line, there may be no need for the backslash \ to mask the newline because the pipe | symbols can be used for formatting your code as well.

# example
ls | 
 cat -n | 
 tail   | 
 head
marko
  • 111
  • 2
  • 5
    +1. Same with `&&` and `||` – glenn jackman Jul 08 '13 at 10:22
  • 1
    oh my, +1, before seing this I always did "commands \ | commands" (which has the advantage of being quite readable, though, as the pipe begin the line, clearly visible. But having to remember to add the "\" makes it cumbersome) – Olivier Dulac Jul 09 '13 at 09:11
  • Related: [Where are bash line continuations after && and || documented?](http://unix.stackexchange.com/q/253518/135943) – Wildcard May 13 '16 at 20:50