Reputation: 12837
Is there any way to save the command into bash history as the multiline command and then to navigate up and down to make some edits and run it again?
$ shopt -s cmdhist
$ shopt -s lithist
$ echo "1"\
&& echo "2"\
&& echo "3"
Now, if I hit the up-arrow I'd like to see the
$ echo "1"\
&& echo "2"\
&& echo "3"
..again, but bash gives me the echo "1"&& echo "2"&& echo "3"
. I.e. it removed the new lines although the cmdhist
and lithist
flags are set.
If the up-arrow worked and displayed the multi-line command, how can I navigate up and down in it?
Upvotes: 6
Views: 2658
Reputation: 5531
.... displayed the multi-line command, how can I navigate up and down in it?
You can't navigate up and down in a multi-line command from the history, because bash is saving the command as a single line with embedded new lines or semicolons (depending on lithist
). Navigating by word does work though, and jumps across the embedded newlines: Alt-Left/Right
.
Alternatively, the key-combo Ctrl-x Ctrl-e
opens the multi-line command in a text editor so you can edit it comfortably. Then if you save and quit the editor, bash will echo the command back and run it.
The default editor is set using the VISUAL and/or EDITOR environment variables. To cancel executing the command after you're in the editor, completely erase the contents of the file before saving it and quitting the editor.
Upvotes: 1
Reputation: 2761
I'm sure the OP has moved on to new challenges, but for posteriority:
If you are using &&
to make these three commands into one to keep them in one single history entry (rather than to abort on error), consider instead making a parenthesized command:
$ (echo "1"
echo "2"
echo "3")
The parenthesized expression is treated as a single command and if you have shopt -s lithist
the newlines are preserved.
Be aware though that commands within are executed in a subshell. Any variable assignments made are discarded after the command completes and the subshell is exited.
Upvotes: 1
Reputation: 12383
It's not possible in Bash
as \
before a newline is ignored in Bash
. From man bash
:
A non-quoted backslash () is the escape character. It preserves the literal value of the next character that follows, with the exception of . If a \ pair appears, and the backslash is not itself quoted, the \ is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).
If you're willing to change your shell or want to experiment check out zsh
, it can do what you're looking for:
$ echo a \
echo b
Press C-p and see that newlines are retained:
$ echo a \
echo b
Upvotes: 6