3

I read a few articles, but having little to no knowledge of bash script I'm unable to do what I need. like I tried this SO post

I've a function in .bash_alias as follows, which simply cd into server folder.

html() {
  cd /var/www/html/$1
}

So in command html myapp it executes cd /var/www/html/myapp. This is all fine. I want to take to to Next level.

I want to do html my<TAB> so that it auto completes into html myapp Not to hard-code any folder, I want to have the usual default auto completion behavior. If there are multiple folder start with my in the name, list folders maybe as well. Please guide.

Abdul Rehman
  • 184
  • 1
  • 10

1 Answers1

3

You need to write a completion function (conventionally, we'd name it _html). Then associate that function with the html command using the complete builtin:

_html() {
    local cur prev words cword
    _init_completion || return
   COMPREPLY=($(cd /var/www/html && compgen -o dirnames -- "$cur"))
}

complete -F _html html

(Note: _init_completion is defined in /usr/share/bash-completion/bash_completion, which I assume you've already sourced - either directly, or via /etc/bash_completion)

Toby Speight
  • 8,460
  • 3
  • 26
  • 50
  • 1
    OMG, This is Magic. Thank you sense. Could maybe guide me what should I study to know stuff like this? linux home user since a couple years, but no admin experience at all. Would love to start now. – Abdul Rehman Jan 13 '20 at 15:17
  • 1
    Just study the man pages and the existing code; look in `/usr/share/bash-completion/` for the completions you have installed, and follow along until you understand how they work. – Toby Speight Jan 13 '20 at 15:24
  • 1
    @Bsienn `man complete` – user234461 Jan 13 '20 at 15:42
  • @user234461, ITYM `man bash-builtins`, given that this is Ubuntu. – Toby Speight Jan 13 '20 at 16:31
  • @TobySpeight It's usual to overwrite the Ubuntu man pages from a Fedora install after each `apt` update so `man complete` is actually more likely to be useful – user234461 Jan 13 '20 at 16:34
  • I've never heard of writing Fedora man pages onto an Ubuntu system - that doesn't sound "usual" to me! – Toby Speight Jan 13 '20 at 16:39