5

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 )
12

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 8 '13 at 8:46
  • yeah copy and paste is a curse! :) – Raphael Ahrens Jul 8 '13 at 8:48
  • I checked it and it works even having indentations! – coffeMug Jul 8 '13 at 8:54
  • 1
    @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 8 '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 9 '13 at 9:14
10

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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