I've got a bash function called repos in my .bash_profile, for which I'd like to add autocomplete functionality that lists out the contents of a particular directory. I'm trying to achieve this using the complete command.
In short, what I've tried:
Created a file called repos_complete.bash containing the code below. I've thereafter run source repos_complete.bash to make sure it applies to the repos script.
Code in repos_complete.bash:
complete -A directory repos
Result so far: If I enter repos, and press tab, it will list out the contents of the current directory. What I'd like however, is for it to list out the contents of another dir, like e.g. ~/source/repos/.
I tried to to this by replacing the contents of repos_complete.bash with the following:
complete -C ls ~/source/repos repos
When entering repos and tab now however, I get an error message:
Cannot access 'repos': no such file or directory
It appears to me as if the -C (which accepts a command afterward) is interpreting the whole line as a command, including the last "repos", instead of just applying the first part (ls ~/source/repos) as a command to the function repos, which is what I'm trying to achieve.
Any tips on the correct way to pass the ls <some path> command in the correct way here?
Note: I should point out that this is running in the context of a git bash shell under windows 10, in case that should make any difference.
I think that you would need to fill the COMPREPLY array. I think this could work:
_repos()
{
local cur;
local base=~/source/repos/
_get_comp_words_by_ref cur;
cur="$base$cur"
_filedir
COMPREPLY=("${COMPREPLY[@]#$base}")
} && complete -o nospace -F _repos repos
If you want to use the -C option, you can use this method below. (Note that I have not evaluated it for file-names containing special characters.)
_repos()
{
( cd ~/source/repos; printf "%s\n" "$2"* )
} && complete -o nospace -C _repos repos
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With