Bash: How to output command to next prompt for user to use?

Solution 1:

If you are using X, the xdotool tool might be a solution, by including in the script a command such as :

xdotool type command-line-to-display

If the new text becomes mixed with the script output, some acrobatics might be required.

Solution 2:

Add these lines at the end of your bash script:

MY_COMMAND="ls"
MY_PARAMS=()
read -a MY_PARAMS -p $MY_COMMAND 
exec $MY_COMMAND ${MY_PARAMS[@]}

This assumes that the command you want to execute is ls, change it as it suits you. What you enter is stored as an array called MY_PARAMS, initialized by the first line; the command is then executed by repeating the command followed by the expansion of the array variable, which means all of its elements. The above is independent of how many elements you pass to your command. The exec shell command replaces the shell with the given command, effectively terminating your script.

EDIT:

If you want to add full command editing capabilities to your script, much beyond what read -e has to offer, you can do as follows: install rlwrap, then add the following code at the bottom of your Bash script:

stty -ixon
MYINPUT=()
HISTORY=$HOME/.bash_history
MYCOMMAND="ls"
MYINPUT=$(rlwrap -H $HISTORY -P $MYCOMMAND sh -c 'read REPLY && echo $REPLY')
stty ixon
exec sh -c "${MYINPUT[@]}"

rlwrap is a program which is capable of using all the features of readline, unlike the very poor Bash read -e option. It allows you to specify a file where to search for possible completions (I used the Bash history, $HOME/.bash_history, above, but you can write your own file). Also it can be configured (see the inputrc section in the readline manual) so you can choose between Emacs-style and vi-style editing, and allows you to search for matches forward (Ctrl+r) or backward (Ctrl+s) in the history file, edit the commands, and much much more.

I have added the stty -ixon/set ixon options because most terminal emulators intercept the control sequences Ctrl+r and Ctrl+s, and so on, and this disables this feature for the time being.

Also, the command you wish (I used ls for illustrative purposes) is pre-loaded, and can be executed as is (by hitting return) or modified via the readline capabilities of rlwrap.

What the above cannot do is to display a list of possible matches, allowing you to choose by means of your keypad. This requires some BASH programming (see dirkt's answer).

Solution 3:

Not a full answer, but an explanation of what you've seen:

You can have a look at how qfc does it by inspecting qfc.sh. It uses special features of two shells: For zsh, the zle command, and for bash, the READLINE_LINE variable. Also, both variants use a function that is invoked within the shell, they don't just start a script and and make that information available on exit.

Doing it in a shell-independent way on exit of a script is an interesting problem. :-)