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,884

2 Answers2

16

You can mask the newline with \.

$( com\
aaaaaaaaaaaaaa\
aaaaaaaaaaaaaa\
nd )

The \ tells the shell to ignore the newline.

  • 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\<NEWLINEHERE>ho a), works while echo $(ec\<NEWLINE HERE><INDENTATION HERE>ho a) produce ec: command not found. While echo $(echo Hello,\<NEWLINE HERE> World)[note the space after newline] and echo $(echo Hello,<NEWLINE HERE><INDENTATION HERE> 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,\<NEWLINE HERE> 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 "\<NEWLINE><indentation>something is equivalent to \<NEWLINE><anotherindentation>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