Can bash write a command to the terminal input?

Viewed 2455

I have a long winded command. I created a bash function to make it easier to remember.

For example:

phew() {
   echo 'This is not really my super long winded command'
}

This is all great. However, I don't want to execute the command yet. I just want phew to do all the typing for me.

Is there a way to write a string of text to the terminal input?

Adapting the example above:

phew() {
  foo "echo 'This is not really my super long winded command'"
}

$ phew # would write the next line for me
$ echo 'This is not really my super long winded command' # Then, I press enter. Producing...

# This is not really my super long winded command
4 Answers

Try one of these:

  1. bash required:

    phew() {
      printf '%s' "Type something: "
      read c < <(echo $@)
      echo $c
    }
    

    (Delete the second echo to just run the input string.) Test:

    phew Tro lo lo lo LO
    

    Output:

    Type something: Tro lo lo lo LO
    
  2. Plain old Bourne shell:

    phew() {
        c="echo 'This is not really my super long winded command'"
        read -p "Hit enter to run: $c"
        $c
    }
    

    Test:

    phew
    

    Output:

    Hit enter to run: echo 'This is not really my super long winded command'
    

    ...user hits Enter. Output:

    'This is not really my super long winded command'
    

    This can be more dangerously generalized to:

    phew() {
        c="$@"
        read -p "Hit enter to run: $c"
        $c
    }
    

    Where the user would type phew "echo 'yadda yadda'". It's safer to only use a function like that in a script to save the programmer the bother of writing different versions of phew.

You can create an alias, then use M-C-e (Ctrl+Alt+e on PC keyboards) to expand it.

alias phew="echo 'This is a very long command'"

after which typing phew followed by M-C-e will leave echo 'This is a very long command' on the command line.

Caution: M-C-e will expand everything on the command line, including command substitution (backticks) which will cause the enclosed command to be executed. Make sure that is what you want. There is a separate readline function to only expand aliases; by default it isn't bound to a key, but you could bind it to one.

I found a way, but it's not really what I am looking for. It's far too specific on the environment.

Requires AppleScript and iTerm2.

Therefore, it only works on a mac.

write_noline() {
  osascript \
  -e "tell application \"iTerm2\" to tell current window to tell current session to write text \"${@}\" newline NO"
}

Using the example:

phew() {
  write_noline "echo 'This is not really my super long winded command'"
}

enter image description here

You can maybe put the rest of your text as a argument

script:

ls "$1"

command line:

>script '/home/me/Pictures'
Related