Here's a shell script that does some stuff according to with what parameter it was called:
if [ $1 = "-add" ]
then
...
elif [ $1 = "-remove" ]
...
else
...
fi
A script is an executable one (a link to it was created in the /usr/bin
directory). So, I can call it from shell by specifying the link name added in /usr/bin
.
What I want, is auto-detecting the possible arguments of script (in my case they are -add
, -remove
) during it calling. It means that when I'll type a command, related to script calling, then type -re
and press a tab button it will suggest that it's -remove
and autofill it for me.
How the arguments need to be defined to reach that?
Tried to create aliases in shell config file or few links in /usr/bin
directory for all possible inputs and it was working fine, but I don't think it's a best solution for that.
While it does require some configuration outside of your script, adding autocomplete options is fairly easy.
Here's a simple example of a ~/.bash_completion file that adds auto completion of --add and --remove to command yourscript. In a real world case you'd probably want to generate the options by querying the script directly; they're hard coded here for simplicity.
_yourscript_complete()
{
# list of options for your script
local options="--add --remove"
# current word being completed (provided by stock bash completion)
local current_word="${COMP_WORDS[COMP_CWORD]}"
# create list of possible matches and store to ${COMREPLY[@}}
COMPREPLY=($(compgen -W "${options}" -- "$current_word"))
}
complete -F _yourscript_complete yourscript
Note that the ~/.bash_completion is only sourced during login, so you'll need to spawn another login shell to see your changes in action. You may need to enable sourcing of user bash_completion files on your system, too.
The result:
$ yourscript --<tab><tab>
--add --remove
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