I have written a really long command in bash, how can I break in to several lines?

Viewed 867

I need to run a series of long-lines of bash commands. In each series, there is a need to change some parameters and run the command again; and it becomes messy very soon.

The best case is to break the lines with "\", but that is only possible if I am adding parameters to the end of the command.

I want to know how can I inject a newline in the middle of long command, something like Shift+Enter or Ctrl+Enter in most editing environments.

This is a sample command; and I want to reformat it from:

$ execute_command -a /path/to/file -b another_option -c third_option

to:

$ execute_command \
> -a /path/to/file \
> -b another_option \
> -c third_option
1 Answers

The v is technically "unbound" in most documentation, but when I am typing on the command line (in vi mode) and need to edit I hit <ESCAPE>v. I run in vi mode all the time (set -o vi), so this drops my whole current command buffer into a vi session where I can use the full power of the editor to add line breaks, correct spelling and punctuation, rethink my logic, etc. before submitting the buffer. When you save and exit vi, the saved buffer is fed to the parser a line at a time as if you'd done them sequentially on the command line.

Just be aware that when you exit, the buffer WILL execute whether you save or quit with no changes, so if you don't want it to do anything, save your work somewhere with :w somefile, then delete ALL the lines and SAVE the buffer as you exit. An "empty" buffer is the only no-op.

I can't find documentation on this at the moment, but I've used it for decades in HPUX & SunOS ksh as well as various versions of linux bash.

Otherwise, I recommend copy, cancel, paste into your favorite buffer/editor, fix it, copy, then paste back into the command line, lol


### Old Answer
As you said, backslash-escape a newline and the parser will effectively ignore it.
$: echo \
> this \
> is \
> all
this is all

Just make sure it is the LAST character of that line.
c.f. this page for more.

Any properly quoted newline can be included in your output, since they are now part of the data.

$: echo "
> this
> is
> all"

this
is
all

You can also pass them as data individually.

$: echo this $'\n' is $'\n' all
this
 is
 all
Related