Bash Alias with Argument and Autocompletion

bash alias with argument and autocompletion

If your function is called "foo" then your completion function could look like this:

If you have the Bash completion package installed:

_foo () { local cur; cur=$(_get_cword); COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }

If you don't:

_foo () { local cur; cur=${COMP_WORDS[$COMP_CWORD]}; COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }

Then to enable it:

complete -F _foo foo

The command compgen -c will cause the completions to include all commands on your system.

Your function "foo" could look like this:

foo () { cat $(type -P "$@"; }

which would cat one or more files whose names are passed as arguments.

Bash Autocompletion with multiple argument values per argument

You can try this

_autocomplete () {
COMPREPLY=()
local cur=${COMP_WORDS[COMP_CWORD]}
local prev=${COMP_WORDS[COMP_CWORD-1]}

if [[ ${cur} == -* ]]
then
COMPREPLY=($(compgen -W "--option_a --option_b" -- $cur ) )
return 0
fi

case "$prev" in
--option_a|bread|pizza|steak|burger)
COMPREPLY=( $( compgen -W "$OPTION_A_VALUES" -- $cur ) )
return 0
;;
--option_b|apple|banana)
COMPREPLY=( $( compgen -W "$OPTION_B_VALUES" -- $cur ) )
return 0
;;
esac

}

The idea is

If the cur starts with -, the compgen gets option_a option_b immediately

If the prev is one of --option_a bread pizza steak burger, it gets the values again

How do I get bash completion to work with aliases?

As stated in the comments above,

complete -o default -o nospace -F _git_checkout gco

will no longer work. However, there's a __git_complete function in git-completion.bash which can be used to set up completion for aliases like so:

__git_complete gco _git_checkout

bash alias not autocompleting same as aliased

If we look at the completion for command 'vlc' we see:

$ complete | grep vlc
complete -F _minimal vlc

so the wrapper function is "_minimal". We can use the same for the new command:

$ alias watch='vlc'
$ complete -F _minimal watch

and subject must be now solved.

Alias with Argument in Bash - Mac

Bash aliases don't support arguments, so you need to use a bash function, and use the bash arithmetic operator $(())

function mins_ago() {
printf "%s" "$(( $(date +%s) - (60 * $1) ))"
}

Add the above function in .bash_profile, and now testing it in the command-line,

date +%s
1485414114

value="$(mins_ago 3)"
printf "%s\n" "$value"
1485413834

(or) without a temporary variable to convert to readable format in GNU date, do

printf "%s\n" "$(date -d@$(mins_ago 3))"


Related Topics



Leave a reply



Submit