Set working directory for function arguments

My code is in the following directory on my computer / a / b / c / d / e / myCode. It annoyed me to type make / a / b / c / d / e / myCode / project1 when I wanted to compile project1. To fix this, I created a function in my bashrc that looks like this:

function make_project { make /a/b/c/d/e/myCode/$1; } 

Then I call it like this:

 make_project project1 

It works great. The only problem is that I do not have autocomplete for project1. Therefore, if I have a project with a complex name, for example my_complicatedly_named_project, I will need to enter an integer name. Is there any way for bash to know that the arguments are directories in / a / b / c / d / e / myCode / and it can autocomplete accordingly?

+5
source share
3 answers

The compgen command can be used to generate and test completions, and looking at existing improvements can help create new ones. You are behind directories in a specific subtree, so the following should work in bash:

 function _make_project { COMPREPLY=( $(cd /a/b/c/d/myCode; compgen -A directory -- "${COMP_WORDS[COMP_CWORD]}") ); } 

This uses compgen to get directories that can complete the current argument, starting with the myCode subtree. To set this for your function, you must use the complete command to bind this completion function using the bash function:

 complete -F _make_project make_project 

Update

To avoid using the space character for shutdown, the nospace option may be provided when registering the shutdown function. If this is combined with the -S option to compile to add a suffix character, then terminations can be displayed as directory names, and you can easily smooth out the subtree:

 function _make_project { COMPREPLY=( $(cd /a/b/c/d/myCode; compgen -S / -A directory -- "${COMP_WORDS[COMP_CWORD]}") ); } complete -o nospace -F _make_project make_project 
+2
source

I don't know if bash can do this, but zsh can do it wisely. To make this work in zsh, add this line to .zshrc:

 fpath=(~/.zshcompletion $fpath) 

Then create the file ~/.zshcompletion/_make_project :

 #compdef make_project # _arguments "1: :(World)" _make_project() { # Note: Do the following two lines mean anything?: local curcontext="$curcontext" state line typeset -A opt_args for dir in /a/b/c/d/e/myCode/*(/); do compadd " $@ " "${dir/*\//}" done } 

Note. I know this is not the answer you asked, but since zsh has basically the same user interface as bash (with scripts that are usually compatible), I figured this could be useful if there isn’t a simple bash.

0
source

Use the soft link for the myCode directory.

 ln -s /a/b/c/d/e/myCode/ ~/myCode 

Change your function to:

 function make_project { make $1; } 

I believe that adding extra myCode will not hurt too much:

 make_project ~/myCode/project_name 

or just use make :

 make ~/myCode/project_name 

You can also use autocomplete after typing ~/myCode/

0
source

Source: https://habr.com/ru/post/1209694/


All Articles