bitcoin.bash raw
1 # bash programmable completion for bitcoin(1) wrapper
2 # Copyright (c) 2026-present The Bitcoin Core developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 # wrapper to delegate completion to the real function
7 _bitcoin_wrap() {
8 local delegate="$1" shift_count="$2"
9 local func="_${delegate//-/_}"
10 local words cword dir file
11
12 # load completion script if function not yet defined
13 if ! declare -F $func >/dev/null; then
14 dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
15 file="$(grep -l -E "complete[[:space:]]+-F[[:space:]]+${func}" "$dir"/* 2>/dev/null | head -n1)"
16 [ -z "$file" ] && file="$(grep -l -E "^[[:space:]]*${func}[[:space:]]*\(\)" "$dir"/* 2>/dev/null | head -n1)"
17 [ -n "$file" ] && source "$file" || return 0
18 fi
19
20 _get_comp_words_by_ref -n = words cword
21
22 COMP_WORDS=( "$delegate" "${words[@]:$shift_count}" )
23 COMP_CWORD=$(( cword - (shift_count - 1) ))
24 COMP_LINE="${COMP_WORDS[@]}"
25 COMP_POINT=${#COMP_LINE}
26 $func "$delegate"
27 }
28
29 _bitcoin() {
30 local cur prev words cword
31 local bitcoin subcmd offset
32
33 # save and use original argument to invoke bitcoin for help
34 # it might not be in $PATH
35 bitcoin="$1"
36
37 COMPREPLY=()
38 _get_comp_words_by_ref -n = cur prev words cword
39
40 case "${words[1]}" in
41 -m|-M|--multiprocess|--monolithic)
42 subcmd="${words[2]}"
43 offset=3
44 ;;
45 *)
46 subcmd="${words[1]}"
47 offset=2
48 ;;
49 esac
50
51 case "$subcmd" in
52 gui|node)
53 _bitcoin_wrap bitcoind "$offset"
54 return 0
55 ;;
56 rpc)
57 _bitcoin_wrap bitcoin-cli "$offset"
58 return 0
59 ;;
60 tx)
61 _bitcoin_wrap bitcoin-tx "$offset"
62 return 0
63 ;;
64 esac
65
66 case "$cur" in
67 -*=*) # prevent nonsense completions
68 return 0
69 ;;
70 *)
71 local options commands
72
73 # only parse help if sensible
74 if [[ -z "$cur" || "$cur" =~ ^- ]]; then
75 options=$($bitcoin help 2>&1 | awk '{ for(i=1;i<=NF;i++) if ($i~/^--/) { sub(/=.*/, "=",$i); print $i } }' )
76 fi
77 if [[ -z "$cur" || "$cur" =~ ^[a-z] ]]; then
78 commands=$($bitcoin help 2>/dev/null | awk '$1 ~ /^[a-z]/ { print $1; }')
79 fi
80
81 COMPREPLY=( $( compgen -W "$options $commands" -- "$cur" ) )
82
83 # Prevent space if an argument is desired
84 if [[ $COMPREPLY == *= ]]; then
85 compopt -o nospace
86 fi
87 return 0
88 ;;
89 esac
90
91 } &&
92 complete -F _bitcoin bitcoin
93
94 # Local variables:
95 # mode: shell-script
96 # sh-basic-offset: 4
97 # sh-indent-comment: t
98 # indent-tabs-mode: nil
99 # End:
100 # ex: ts=4 sw=4 et filetype=sh
101