How to get tab autocompletion in bash to replace an expanded $(command)?

Viewed 51

I have a small bash script get_path that takes in an argument and returns a predetermined path to stdout. For example, I can use it to copy a file to a "project1" directory in the following way:

$ cp file1 $(get_path project1)

In above example $(get_path project1) expands to something like /path/to/project1/. To copy the file to /path/to/project1/dir1/ I want to be able to use autocompletion and do something like:

$ cp file1 $(get_path project1)/d<tab_key>

When I try this, bash autocompletes it to:

$ cp file1 $(get_path /path/to/project1/dir1/

i.e., the $(get_path part is not replaced. How do I fix this?

1 Answers

You can use the shell-expand-line readline command for this, usually bound to Esc,Ctrl-e:

$ bind -P | grep shell-expand-line
shell-expand-line can be found on "\e\C-e".

For example, type echo "$(echo foo)", press and release Esc followed by Ctrl-e, and the command is replaced with echo foo.

Related