Search code examples
linuxbashcommand-lineprompt

In a bash script, print command (as a suggestion) on the prompt after the script exit


I'd like to write a shell script that can suggest a command by printing it after the command line prompt. Then, after the scrip exit, the user would only have to press the [enter] key to run this suggested command.

Given that I'm new to bash, I don't even know if it is possible to do this. I thought about using a copy-past command, moving the cursor, use the $PS1 variable, without finding a suitable way..

Does anyone have any clues on how such feature could be implemented ?


Solution

  • Following the suggestion of Landen in the comments (thanks a lot!), I've been able to produce a workaround for my problem.

    This workaround needs the xautomation package (xte command, emulating key pressed), is not very robust, and may depends on the keyboard layout handling of xautomation, and system shortcuts. For example, I had to change the shortcut for the unity HUD.

    But given that my command is very fast, and that is is mostly for personal use, this solution fits perfeclty my needs:

    COMMAND_PASSED='sudo apt-get update'
    
    # Displays the content of $COMMAND_PASSED on the next prompt
    xte "str $COMMAND_PASSED"
    sleep 0.1
    tput cub ${#COMMAND_PASSED}
    

    sleep 0.1 and tput cub ${#COMMAND_PASSED} commands are needed to prevent the keys from being also displayed before the command prompt.

    sleep 0.1 makes the whole command to be printed before the prompt.

    tput cub ${#COMMAND_PASSED} move the cursor backward to make sure that all unnecessary prints are erased.

    Thanks everyone!