RSS Feed Share on Twitter

All Shell Scripting Tips

25 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 $VISUAL varible says; if that's not set, then it will use $EDITOR, or fall back to emacs if neither are set.
  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).

 

 


You can buy the content of this tutorial as a PDF to download to all of your devices!

Contact

You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!