The Shell Scripting Tutorial


Editing a line in a text editor

Copy a command into a text editor for further editing

25 March 2017

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).


My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.

Shell Scripting Tutorial

Shell Scripting Tutorial
is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion.

Also available in PDF form from Gumroad:Get this tutorial as a PDF
Shell Scripting: Expert Recipes for Linux, Bash and more

Shell Scripting: Expert Recipes for Linux, Bash and more
is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script.