Clear command from terminal in OS X
Assuming you're in bash, use Ctrl + U.
Many programs that wait for you to type a command line and then execute that line, including bash, take Ctrl+C to mean “Abort the current task and go back to the main prompt”.
A few programs, including bash, take Ctrl+U(Clear command from terminal in OS X) to mean “erase the beginning of the line, up to the cursor” (or “erase the whole line”).
In bash, observable differences between Ctrl+C and Ctrl+U include:
- You can undo Ctrl+U, but not Ctrl+C.
- Ctrl+U retains the part of the line after the cursor, if any.
- Ctrl+U erases the affected text from the screen; Ctrl+C shows a new prompt below the current line.
Sometimes you want to stop typing a command but enter it in the shell history to run later. A useful trick is to put a #
at the beginning of the line and execute it: since the line is now a comment, it won't do anything. In bash, there is a single-key shortcut: Alt+#.
There is a readline
function that is probably not bound to a keystroke called kill-whole-line
that will kill the whole line as opposed to only killing the part before the cursor (unix-line-discard
which is somewhat of a misnomer and is bound to Ctrl-u).
You can bind that to any available keystroke. I like ShiftAlt-U since it's a related function. That keystroke may be bound to do-lowercase-version
which means it does whatever the unshifted version does (in this case upcase-word
). Since we don't really need two keys to do that, let's use that one.
You can try it out at the command line by creating the binding this way:
bind '"\eU":kill-whole-line'
or make it persistent by putting this line in your ~/.inputrc
file:
"\eU":kill-whole-line
To undo a Ctrl-u or ShiftAlt-U (or any operation that can be undone), press Ctrl-Shift-_ (underscore) or Ctrl-x Ctrl-u (two keystrokes). Or you can paste back in (yank) what you killed by pressing Ctrl-y which can be repeated if you want multiple copies of that text.
By the way, if you want to kill text from the cursor to the end of the line, you can press Ctrl-k. So instead of doing the binding described above, you can kill a whole line by pressing Ctrl-u Ctrl-k. Only the part killed by the second of those keystrokes will be saved in the kill buffer, but you can still do undo twice to recover them both.