LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   Push output string from script directly into bash / readline command input buffer (http://www.linuxquestions.org/questions/linux-software-2/push-output-string-from-script-directly-into-bash-readline-command-input-buffer-928361/)

GreyBeard 02-08-2012 02:25 PM

Push output string from script directly into bash / readline command input buffer
 
Hi,

I have an application (bash script) which looks at certain conditions on a machine and generates a bash command to deal with those conditions. Trouble is that sometimes the generated command is not exactly what a user wants so the user has to be able to edit the command before it is executed.

The way it works right now is that my script just outputs the generated command to STDOUT, then the users cut and paste the command into the command line prompt, and finally they use the command as is or change it as needed using the readline() command editing capabilities built into bash.

What I would like to do is have my script put the proposed command directly into readline's input buffer and have it displayed after the prompt ready for editing just as if the users had done the cut and paste themselves.

Any idea how I might do that short of modifying bash or readline?

Thanks in advance.

Jeff B.

kbp 02-08-2012 08:20 PM

Code:

OUTPUT=$(some_command)

read -e -i $OUTPUT -p "Cmd to run: " ANSWER

if [[ -z "${ANSWER}" ]]
then
    echo "Nothing entered"
else
    $ANSWER
fi

.. adjust as required - while loops etc ...

David the H. 02-11-2012 04:48 AM

To expand on kbp's answer, you need read's "-e" option so that it uses readline for the input field, and "-i" to insert the default text to modify. Another nice side effect of using readline is that it also allows tab completion.

"help read" and "man bash" for more details.

Note that these options are bash extensions, and likely won't work in other shells.

GreyBeard 02-20-2012 11:26 PM

Thanks for your answers. That solves my problem.

I did have to improve on one aspect of the suggested solution. I know I
said my script generated "a bash command" but what I really meant was that
it generated a string of single commands separated by semicolons the sum
of which constituted (in my view) "a command". I solved that problem by
modifying the script above to be as shown below, then it all worked.

Thanks again.


OUTPUT=$(some_command)

read -e -i $OUTPUT -p "Cmd to run: " ANSWER

if [[ -z "${ANSWER}" ]]
then
echo "Nothing entered"
else
eval "$ANSWER"
fi


All times are GMT -5. The time now is 10:36 AM.