<<< Back to Tips Index

25th March 2017

Editing a line in a text editor

Copy a command into a text editor for further editing

Sometimes, when you are working in an interactive shell, you find that you actually want to edit the current command line in a text editor. Typically, when you have finally crafted the exact command that you would like to use in a shell script. Before I learned this technique, I would typically use a mouse to select the text, copy it into the Copy/Paste buffer, then open a text editor, and paste the command into the text file.

That is a terribly inefficient way to do it!

If you are using the Bash shell (and if you aren't sure, it's more than likely that you are using Bash), you can use this simple control sequence instead:

Step 1: Select the line you want to edit

For example, here I've created a fine Shakesperean script:

question

Step 2: Press ^X^E

Hold down the CTRL key, then press x followed by e. That is, CTRL-x followed by CTRL-e.

Step 3: Edit the file

A text editor will be opened, with a randomised name, such as /tmp/bash-fc-143565911346010582, and with the selected line as its contents.

text editor window

Next Steps

From there, you can edit the script as you see fit - such as formatting it more nicely, for example: script

Things to Note

  1. The file will not be created until you choose to save it in the text editor. You will have to give it a new name.
  2. The file will be opened by whatever the $EDITOR variable says, or vi by default.
  3. The command will be executed after you exit the text editor. There doesn't seem to be a way to avoid this (but please contact me if you know of a way).

Invest in your career. Buy my Shell Scripting Tutorial today:

 

Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon