linuxbashshell

How to enter text at command prompt from shell script without executing command?


Is there a way to have a shell script output text at the command prompt WITHOUT issuing the command?

CONTEXT: I SSH into a particular machine several times a day, and about 80% of the time, I type the same three commands as soon as I login. I would just put these commands in my .bashrc, but 20% of the time, I do NOT want to issue these commands. I'm wondering if there is some command I can put in .bashrc that will automatically put a string at my command line, so that when I login I see:

$ cd some/dir && ./some_script.sh

I could then just press enter 80% of the time or just clear the text the other 20% of the time.


Solution

  • (Inspired by Abdul Rehman's answer.)

    Put this as the last line in your .bashrc file:

    read -e -p "(Control-C to cancel) $ " -i "cd some/dir && ./some_script.sh" && eval "$REPLY"
    

    If you hit Enter, read sets the value of REPLY and exits with status 0, causing the following eval to execute. (Usually, eval is not a good command to use; however, here you would be presented with an interactive shell anyway, so there's not much risk here.) If you type Control-C instead, read exits with status 1 and the following eval is not executed, leaving you at your command prompt.