1

My purpose is to quickly retrieve saved bash commands and edit the commands in the bash command buffer (e.g. changing arguments, to experiment with long complex commands). When I press Enter, the command will execute, and pressing Arrow Up, will get me the command again for further editing.

For example, I have a text file called textfile, with the following contents: ls -l
I want to get that file content into the command buffer so that I get
user@ubuntu:~$ ls -l
Because now I can modify and re-execute it.

If I add the execute bit to textfile, I can execute it, but pressing Arrow Up, sets the ./textfile command into the command buffer, not the contents.

Similarly if I enter $(<textfile) it also executes the command, but pressing Arrow Up, just gives me the $(<textfile) command, not its contents

The only solution I can think of is to do cat textfile and then copy / paste the contents into the terminal window. Well, I could also edit the file, save it, and execute it, but that's a hassle to do each time. So, is there a trick to get the contents of a file into the command buffer without typing or pasting?

  • Would the edit-and-execute-command readline command help? C-xC-e start $VISUAL which on my machine is vim, there :r textfile then :x. That will execute the command and from that moment will be available through the history too (unless some configuration explicitly forbids it). – manatwork Aug 9 '17 at 9:47
  • That will help, thanks, although I had hoped for a slightly easier way, like a shortcut in bash itself – jseg-rth Aug 10 '17 at 13:43
1

The command buffer you are referring to is the bash history file... a history of bash commands. The history buffer is written to ~/.bash_history when you log out of the terminal. It's loaded into the buffer when you log in.

You can get the line you want into your bash history buffer by appending the line to your ~/.bash_history file, then manually reloading your bash history file into your buffer with the history -r command.

This is an example:

$ echo "command wanted" >> ~/.bash_history && history -r

Now when you hit the up arrow you will see "command wanted" in your "command buffer".

With this command line you will see the content of your textfile when you hit the up arrow:

$ echo $(<textfile) && cat textfile >> ~/.bash_history && history -r

Be sure to have your textfile terminated with a newline.

  • You're very welcome! You may consider accepting the answer by clicking the gray checkmark. This gives back to the community making it easy for others to find workable solutions. – L. D. James Aug 10 '17 at 14:14

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.