I have a Bash script that returns a command. I would like to execute the script and let it automatically print the result behind the prompt in the next line. Replacing the script call in the current line would be an option too. This way I could edit the command before I execute it. Can this be achieved within a terminal with Bash?
-
2As an easier-to-implement alternative to this behaviour, you could open an editor containing the command and then source the edited file: `trap 'rm -f -- "$cmd_file"' EXIT; cmd_file=$(mktemp); printf %s\\n "$command" >"$cmd_file"; ${EDITOR:-nano} -- "$cmd_file" && (. "$cmd_file")` – user3035772 Jan 15 '16 at 12:15
-
2@user3035772 Good idea! However, it should be `${EDITOR:-vim}` ;D – hek2mgl Jan 15 '16 at 13:16
-
Related: http://stackoverflow.com/questions/5374255/how-to-write-data-to-existing-processs-stdin-from-external-process – Oleg Andriyanov Jan 15 '16 at 13:23
-
1@hek2mgl I'm a fan of vim, but I thought in this case they key map for nano feels a little more like bash's default key map. – user3035772 Jan 15 '16 at 14:13
-
Well, there are [terminal escape sequence vulnerabilities](http://unix.stackexchange.com/a/15210/17535) that you could try to exploit, but those would be highly non-portable at best. – 200_success Jan 31 '16 at 09:09
2 Answers
If you run bash within tmux (terminal multiplexer), you can use its buffer functions to paste a command at your prompt. You can then edit the command before running it. Here's a trivial example:
#!/bin/bash
tmux set-buffer 'ls -l'
tmux paste-buffer &
Putting the paste-buffer command in the background let's bash output the prompt before the paste happens. If the paste happens too quickly, you can add a sub-second sleep like so:
#!/bin/bash
tmux set-buffer 'ls -l'
{ sleep .25; tmux paste-buffer; } &

- 1,134
- 7
- 10
Other than the "use a temporary file" option given in user3035772's comment one other option would be to use the shell's history for this.
Assuming the command that creates the output is a shell command (or you can be sure its output is only the command you want to run later) you can use history -s
to store a command in the history and then recall it on the command line to edit it (or use fc
to do so).
history -s 'echo whatever you "want your" command to be'
Then use fc
to edit it in your $EDITOR
or hit the up arrow or Ctrl-p to load the history item into the current input line.

- 1
- 1

- 77,877
- 8
- 106
- 148