Monday, December 13, 2021

Create your Bash Completion

 


In this post we will review how to create a bash completion for your project scripts.

As our project grows we add more and more scripts that a developer can manually execute for various development operations. Some of these script require arguments and a bash completion could highly assist the develop, especially when this scripts are often used, and when the argument are long.

My recommendation for this is to add a single bash completion script as part of the project GIT repository. This script should be executed in the bash RC file: ~/.bashrc , for example:

source /home/foo/git/my-project/bash_completion.sh


To provide a static auto-complete, we use a list of values. The following example is a completion for a script that gets the environment name as an argument. 


complete -W "dev staging prod" ./examine-env.sh


In other cases the arguments values are dynamic, for example, we have a parent folder under which we have a folder for each microservice. We have many script that receive a name of a microservice. So we want a dynamic completion with the service name. This is done using the following:


function service_completion(){
if [ "${#COMP_WORDS[@]}" != "2" ]; then
return
fi

local suggestions=($(compgen -W "$(ls ./services-parent-folder | sed 's/\t/ /')" -- "${COMP_WORDS[1]}"))

if [ "${#suggestions[@]}" == "1" ]; then
local value=$(echo ${suggestions[0]/%\ */})
COMPREPLY=("$value")
else
COMPREPLY=("${suggestions[@]}")
fi
}


complete -F service_completion ./build-micro-service.sh



Notice that the auto completion is for an actual used working directory. In case running from another folder, and instead of running ./examine-env.sh you would use ./foo/examine-env.sh , the auto completion would not be invoked.




No comments:

Post a Comment