How can I delete a just-typed newline character in bash?

Solution 1:

Bash uses GNU Readline Library for command-line input and editing. Unfortunately this library processes the input only line by line. The readline() call returns after finishing the line by pressing Enter. Next line (after showing the $PS2 ">" prompt) is processed by a separate readline() call.

When you go back in the editing history to a multi-line input Readline treats the input as a single "line" with newlines (the $PS2 prompts are not displayed) so you can edit the whole multi-line input as you described.

I use the following trick to solve the problem you presented: When I have input with unwanted newline I cancel it by pressing Ctrl+c. Then I return to the cancelled input by pressing (or Ctrl+p). Then I can remove the newline by Backspace and do other edits.

Input with unwanted newline at the end, pressing Ctrl+c:

$ cat 'xyz
> ^C

After pressing the input returns event without the trailing newline:

$ cat 'xyz