9

I sometimes copy-paste paths into the terminal, and often accidentally copy the newline character. For example, I want to find then read the contents of foobar.txt.

$ locate foobar.txt
/home/sparhawk/Document Directory/foobar.txt

I then select the second line with a triple click. (Oops, it selects the trailing newline too!) Since there is a space in the path, I need to enclose the path in quote marks. Hence type in

$ cat '

and middle-click to paste. This produces

$ cat '/home/sparhawk/Document Directory/foobar.txt
> 

since I have inserted a newline before closing the '. At this point, I cannot press backspace to delete the newline. Is there a way to delete this just-typed newline?

More information

At this point I can either SIGINT with Ctrl+c, or complete the quote with another '. Let's say I do the latter.

$ cat '/home/sparhawk/Document Directory/foobar.txt
> '
cat: /home/sparhawk/Document Directory/foobar.txt
: No such file or directory

which makes sense, as I just typed in a path with newline in it. However, at this point, I can press the up arrow, to load the last command. i.e.

$ cat '/home/sparhawk/Document Directory/foobar.txt
'

At this point, I can press backspace twice to delete the newline. (N.B. there is no > in the second from-history example.)

1 Answer 1

7

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
1
  • 1
    Yeah, I had come across that workaround too. It's probably the cleanest way to overcome this. +1 for references, and showing that a workaround is the only solution.
    – Sparhawk
    Oct 8, 2013 at 9:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .