-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.bash_hV3.1.1
More file actions
1182 lines (1031 loc) · 40.2 KB
/
.bash_hV3.1.1
File metadata and controls
1182 lines (1031 loc) · 40.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#========================================================================
# Main Function: h
# Purpose: bash help tool
#========================================================================
__H_version="3.1.1"
__H_extglob_was=0
__H_RHEL_like=0
__H_OLD_PATH="$PATH"
# shellcheck disable=SC2034
__H_needed_deps=(grep basename file find sed cut head readlink realpath perl)
# shellcheck disable=SC2034
__H_optional_deps=(tput fzf batcat bat)
declare -gA __H_SOURCED_FILES_MAP=()
declare -ga __H_SOURCED_FILES_LIST=()
complete -F _h_completion h
h() {
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
trap '_h_restore_path; _h_reset_extglob' RETURN
local cmd ctype
_h_detect_os
_h_add_admin_paths # Setup PATH
_h_enable_extglob
_h_setup_colors # Setup tput or ansi
_h_check_dependencies __H_needed_deps __H_optional_deps 1 # 1 = exit if required deps missing
# -------------------------
# Get command or last command
# -------------------------
if [[ -n "$1" ]]; then
read -r -a fcmd <<< "$1"
else
read -r -a fcmd <<< "$(fc -ln -1)" || {
printf " ↳ %sFailed to get last command%s\n" "$RED" "$RESET"
return 1
}
fi
cmd="${fcmd[0]}"
# ------------------------
# Handle options
# ------------------------
case "$cmd" in
-h|--help) _h_usage; return 0;;
-v|--version) _h_ver; return 0;;
-t|--trace)
shift
[[ -z $1 ]] && { printf "trace requires an argument\n" >&2; return 1; }
_h_print_trace "$1"
return 0
;;
-f|--fzf) _h_fzf_search; return 0;; # alias hf='command -v fzf >/dev/null 2>&1 && h --fzf || h'
esac
if [[ "$cmd" == "h" ]]; then # prevent spamming terminal with h.
_h_usage # prevent spamming terminal with h.
return 0
fi
# -------------------------------------------------------------------------
# handle edge cases
# -------------------------------------------------------------------------
if [[ "$cmd" == "}" || "$cmd" == "[[" || "$cmd" == "]]" || "$cmd" == "]" ]]; then
declare -A __H_KEYWORD_DESC=(
["}"]="Ends a command block."
["[["]="Begins a conditional test expression."
["]]"]="Ends a conditional test expression."
["]"]="Ends a conditional test expression."
)
if [[ -n "${__H_KEYWORD_DESC[$cmd]}" ]]; then
printf "├─ Detected BASH Keyword ${CYAN}'%s' ${RESET}\n" "$cmd"
printf " ↳ ${CYAN}%s${RESET} has no help file\n" "$cmd"
printf " ↳ Definition:\n\n"
printf " ${CYAN}%s${RESET} -- %s\n\n" "$cmd" "${__H_KEYWORD_DESC[$cmd]}"
fi
return 0
fi
# -------------------------------------------------------------------------
# Detect command type
# -------------------------------------------------------------------------
ctype=$(type -t -- "$cmd" 2>/dev/null)
if [[ -z "$ctype" ]]; then
printf "%s├─ ${RED}Unknown or invalid command:${CYAN} '%s'${RESET}\n" "$indent" "$cmd"
printf "%s ↳ Check your spelling and try again\n\n" "$indent"
return 1
fi
# Dispatch by type
case "$ctype" in
alias) _h_show_alias "$cmd" "$ctype" ;;
function) _h_show_function "$cmd" "$ctype" ;;
builtin) _h_show_builtin "$cmd" "$ctype" ;;
keyword) _h_show_Keywords "$cmd" "$ctype" ;;
file) _h_show_external "$cmd" "$ctype" ;;
esac
}
#------------------------------------------------------------------------
# Function: _h_show_alias
# Process aliases
#------------------------------------------------------------------------
_h_show_alias() {
local line_number
local nullglob_was=0
local found_location=""
alias_def=$(alias "$cmd")
printf "├─ ${CYAN}'%s' ${RESET}is an alias:\n" "$cmd"
printf " ↳ Resolves to: ${CYAN}%s${RESET}\n" "$alias_def"
_h_sourcedtree
#----------------------------
# Enable nullglob temporarily
if shopt -q nullglob; then
nullglob_was=1
else
shopt -s nullglob
fi
for file in "${__H_SOURCED_FILES_LIST[@]}"; do
[[ -r "$file" ]] || continue
if grep -qE "^[[:space:]]*alias[[:space:]]+${cmd}=" "$file"; then
found_location="$file"
line_number=$(grep -nE "^[[:space:]]*alias[[:space:]]+$cmd=" "$file" | head -n1 | cut -d: -f1)
printf " ↳ Defined in: ${CYAN}%s (line %s)${RESET}\n" "$file" "$line_number"
fi
done
(( !nullglob_was )) && shopt -u nullglob # Restore nullglob state if we enabled it
#----------------------------
if [[ -z "$found_location" ]]; then
printf " ↳ Declared in: %sinteractive shell (not from a file)%s\n" "$CYAN" "$RESET"
fi
return 0
}
#------------------------------------------------------------------------
# Function: _h_show_function
# Process functions
#------------------------------------------------------------------------
_h_show_function() {
local was_extdebug=0
local func_content
func_content=$(declare -f "$cmd")
#---------------------------
# Enable extdebug temporarily so declare -F includes file/line info
if shopt -q extdebug; then
was_extdebug=1
else
shopt -s extdebug
fi
read -r _ line file <<< "$(declare -F "$cmd")"
(( !was_extdebug )) && shopt -u extdebug # Restore extdebug state if we enabled it
#----------------------------
printf "├─ ${CYAN}'%q' ${RESET}is a shell function\n" "$cmd"
if [[ "$file" == "main" ]]; then
printf " ↳ Declared in: %sinteractive shell (not from a file)%s\n" "$CYAN" "$RESET"
else
printf " ↳ Declared in: ${CYAN}%s (line %s)${RESET}\n" "$file" "$line"
fi
printf " ↳ Showing preview of function: ${CYAN}%s${RESET}\n\n" "$cmd"
_h_highlight_script "$func_content" "$file" "$line"
printf "\n ======= End of function preview =======\n"
return 0
}
#------------------------------------------------------------------------
# Function: _h_show_builtin
# Process builtins
#------------------------------------------------------------------------
_h_show_builtin() {
printf "├─ ${CYAN}'%s'${RESET} is a shell builtin\n" "$cmd"
printf " ↳ Showing ${CYAN}'help %s'${RESET}:\n\n" "$cmd"
help "$cmd" 2>/dev/null | sed "s/^/ /"
return 0
}
#------------------------------------------------------------------------
# Function: _h_show_Keywords
# Handle Keywords and edge cases that fail with type.
#------------------------------------------------------------------------
_h_show_Keywords() {
declare -A __H_KEYWORD_DESC2=(
[then]="Part of an if statement - Begins the command block for a true condition."
[else]="Part of an if statement - Begins the command block if the condition is false."
[elif]="Part of an if statement - Introduces a new condition if the previous one is false."
[fi]="Ends an if statement."
[do]="Begins the body of a loop or conditional block."
[done]="Ends the body of a loop or conditional block."
[in]="Specifies the list to iterate over in a loop."
[!]="Negates the exit status of a command or pipeline."
[esac]="Ends a case statement."
["}"]="Ends a command block."
["[["]="Begins a conditional test expression."
["]]"]="Ends a conditional test expression."
["]"]="Ends a conditional test expression."
)
if [[ $cmd == "(" ]]; then
printf "├─ Detected BASH Keyword ${CYAN}'%s'${RESET}\n" "$cmd"
printf " ↳ ${CYAN}%s${RESET} has no help file\n" "$cmd"
printf " ↳ Definition:\n\n"
printf " ${CYAN}%s${RESET} -- Begins a subshell. Commands inside run in a separate process.\n"
return 0
fi
printf "├─ Detected BASH Keyword ${CYAN}'%s' ${RESET}\n" "$cmd"
if help "$cmd" &>/dev/null; then
printf " ↳ Showing ${CYAN}'help %s'${RESET}:\n\n" "$cmd"
help "$cmd" 2>/dev/null | sed 's/^/ /'
elif [[ -n "${__H_KEYWORD_DESC2[$cmd]}" ]]; then
printf " ↳ ${CYAN}%s${RESET} has no help file\n" "$cmd"
printf " ↳ Definition:\n\n"
printf " ${CYAN}%s${RESET} -- %s\n\n" "$cmd" "${__H_KEYWORD_DESC2[$cmd]}"
fi
return 0
}
#------------------------------------------------------------------------
# Function: _h_show_external
# Process external commands
#------------------------------------------------------------------------
_h_show_external() {
cmd_path=$(command -v "$cmd") || {
printf "${RED}Command not found: '%s'${RESET}\n" "$cmd"
return 1
}
local cmd_real file_info formatted_type output cmdname output_shown help_flags
cmd_real=$(readlink -f "$cmd_path" 2>/dev/null || echo "$cmd_path")
file_info=$(file -b "$cmd_real")
formatted_type=$(printf "%s" "$file_info" | sed -E \
$'s/, interpreter/\\\ninterpreter/g;
s/, version/\\\nversion/g;
s/, dynamically/\\\ndynamically/g;
s/, BuildID/\\\nBuildID/g;
s/, for /\\\nfor /g')
help_flags=(--help -help -h "-?")
output_shown=0
printf "├─ ${CYAN}'%s' ${RESET}is an external command\n" "$cmd"
printf " ↳ Path: ${CYAN}%s${RESET}\n" "$cmd_path"
if [[ "$cmd_real" != "$cmd_path" ]]; then # && \
printf " ↳ ${YELLOW}Symbolic link ${RESET}to: ${YELLOW}%s${RESET}\n" "$cmd_real"
cmd_path="$cmd_real"
cmd="$cmd_real"
fi
if grep -qiE 'script|text executable' <<< "$file_info"; then
printf " ↳ Script Type: \n"
while IFS= read -r line; do
printf " ⎟ ${CYAN}%s${RESET}\n" "$line"
done <<< "$formatted_type"
fi
cmdname=$(basename "$cmd_path")
# Show help or script contents if text executable
if [[ "$file_info" == *"script"* || "$file_info" == *"text executable"* ]]; then
local found_help_flag=""
# Scan the script for common help flags
for flag in "${help_flags[@]}"; do
if grep -q -- "$flag" "$cmd_path"; then
found_help_flag="$flag"
break
fi
done
if [[ -n "$found_help_flag" ]]; then
# Only run the script if a help flag is actually referenced
output=$("$cmd_path" "$found_help_flag" 2>&1 || true)
if [[ -n "$output" ]] && _h_is_help_output "$output"; then
printf " ↳ Showing help from '${CYAN}%s %s${RESET}':\n\n" "$cmdname" "$found_help_flag"
printf "%s\n\n" "$output" | sed "s/^/ /"
return 0
fi
fi
# Fallback: show a preview of the script without executing it
if [[ -r "$cmd_path" ]]; then
printf " ↳ Showing preview of script '${CYAN}%s${RESET}':\n\n" "$cmd"
_h_highlight_script "$cmd_path" " " " "
printf "\n ========== End of script preview =========\n"
fi
return 0
fi
# Show help for external commands
for flag in "${help_flags[@]}"; do
output="$("$cmd_path" "$flag" 2>&1 || true)"
if [[ -n "$output" ]] && _h_is_help_output "$output"; then
printf " ↳ Showing${CYAN} '%s %s'${RESET}:\n\n" "$cmdname" "$flag"
printf "%s\n\n" "$output" | sed "s/^/ /"
output_shown=1
break
fi
done
# Fallback if no help output was shown
if (( output_shown == 0 )); then
local cmd_only="${cmd_path##*/}"
if command -v man &>/dev/null && man -w "$cmd_only" &>/dev/null; then
printf " ↳ Manual available via${CYAN} 'man %s'${RESET}\n" "$cmd_only"
elif command -v info &>/dev/null && info "$cmd_only" &>/dev/null; then
printf " ↳ Info page available via ${CYAN}'info %s'${RESET}\n" "$cmd_only"
else
printf " ↳ ${RED}No help found for ${CYAN}'%s'${RESET}\n" "$cmd_only"
fi
fi
return 0
}
#------------------------------------------------------------------------
# Function: _h_usage
# Purpose : Display usage information and examples for the `h` command analyzer.
#------------------------------------------------------------------------
_h_usage() {
cat <<'EOF'
Usage: h [command]
h is a command resolution engine, h will determine what a command
actually is and try to provide any relevant help that it finds.
Options:
-h --help or h Show this help text.
-v --version Show version information.
-t --trace Command resolution order mapping
-f --fzf Use fzf to interactivly search commands
Examples:
h # Get help for your most recent command
h awk # Get help for 'awk'
h -t awk # Which awk runs and why that one?
EOF
}
#------------------------------------------------------------------------
# Function: _h_ver
# Purpose : Display version information.
#------------------------------------------------------------------------
_h_ver() {
printf "\n h V%s — Bash Command Analyzer\n" "$__H_version"
cat <<'EOF'
MIT License
Copyright (c) 2025 John Blair
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
EOF
}
#------------------------------------------------------------------------
# Function: _h_fzf_search
# start with fzf
#------------------------------------------------------------------------
_h_fzf_search() {
local fzffound=0 pick
if command -v fzf &>/dev/null; then
fzffound=1
fi
if (( fzffound == 1 )); then
pick=$(compgen -A function -A alias -A builtin -A command | sort -u | fzf --prompt="Get help for: ")
[[ -n "$pick" ]] || return 1
h "$pick"
return 0
else
printf " ↳ %sfzf is not installed.%s\n\n" "$YELLOW" "$RESET"
_h_usage
return 0
fi
}
#------------------------------------------------------------------------
# Function: _h_detect_os
# detect os for differences in implementation
#------------------------------------------------------------------------
_h_detect_os() {
__H_RHEL_like=0
if [ -f /etc/os-release ]; then
while IFS='=' read -r key value; do
# Remove surrounding quotes if present
value="${value%\"}"
value="${value#\"}"
case "$key" in
ID)
[[ "$value" == "fedora" || "$value" == "rhel" ]] && __H_RHEL_like=1
;;
ID_LIKE)
[[ "$value" == *"rhel"* ]] && __H_RHEL_like=1
;;
esac
done < /etc/os-release
fi
}
#------------------------------------------------------------------------
# Function: _h_enable_extglob
# Process aliases
#------------------------------------------------------------------------
_h_enable_extglob() {
if shopt -q extglob; then
__H_extglob_was=1
else
shopt -s extglob
fi
}
#------------------------------------------------------------------------
# Function: _h_reset_extglob
# Process aliases
#------------------------------------------------------------------------
_h_reset_extglob() {
(( !__H_extglob_was )) && shopt -u extglob # Restore extglob state if we enabled it
}
#------------------------------------------------------------------------
# Function: _h_setup_colors Colors (tput → ANSI → none)
# Process external commands
#------------------------------------------------------------------------
_h_setup_colors() {
if command -v tput &>/dev/null && [[ $(tput colors 2>/dev/null) -ge 8 ]]; then
# Preferred: tput colors
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
CYAN=$(tput setaf 6)
YELLOW=$(tput setaf 11)
BPURP=$(tput setaf 13)
GREY=$(tput setaf 245) # proper neutral gray
RESET=$(tput sgr0)
UNLINE=$(tput smul)
STOPUNLINE=$(tput rmul)
else
# Fallback: ANSI escape sequences
RED='\033[31m'
GREEN='\033[32m'
CYAN='\033[36m'
YELLOW='\033[93m'
BPURP='\033[95m'
GREY='\033[90m' # safe gray
RESET='\033[0m'
UNLINE='\033[4m'
STOPUNLINE='\033[0m'
fi
: "${RED:=}"
: "${GREEN:=}"
: "${CYAN:=}"
: "${YELLOW:=}"
: "${BPURP:=}"
: "${GREY:=}"
: "${RESET:=}"
: "${UNLINE:=}"
: "${STOPUNLINE:=}"
}
#------------------------------------------------------------------------
# Function: _h_is_help_output
# Purpose: check output to identify binaries that still show help with non zero exit codes
#------------------------------------------------------------------------
_h_is_help_output() {
local text="$1"
# Rule 1: starts with "Usage:"
[[ $text =~ ^Usage: ]] && return 0
# Rule 2: contains OBJECT := definition
[[ $text == *"OBJECT :="* ]] && return 0
# Rule 3: contains common help markers
[[ $text == *"Commands:"* ]] && return 0
[[ $text == *"Options:"* ]] && return 0
[[ $text == *"--help"* ]] && return 0
[[ $text == *"usage:"* ]] && return 0
return 1
}
#------------------------------------------------------------------------
# Function: _h_add_admin_paths
# Purpose: Add ~/.local/bin paths safely and temporarily
#------------------------------------------------------------------------
_h_add_admin_paths() {
# Save PATH if not already saved
if [[ -z "$__H_OLD_PATH" ]]; then
__H_OLD_PATH="$PATH"
fi
local admin_dirs=(
"$HOME/bin"
"$HOME/bin/scripts"
"$HOME/.local/bin"
"$HOME/.cargo/bin"
"$HOME/.npm-global/bin"
"$HOME/.local/share/bash-completion/bin"
"$CONDA_PREFIX/bin"
"/flatpak/bin"
"/snap/bin"
"/usr/local/bin"
"/usr/local/sbin"
"/usr/local/games"
"/usr/bin"
"/usr/sbin"
"/usr/games"
"/bin"
"/sbin"
"/opt/bin"
"/opt/sbin"
)
for dir in "${admin_dirs[@]}"; do
[[ -d "$dir" && ":$PATH:" != *":$dir:"* ]] && PATH="$PATH:$dir"
done
}
#------------------------------------------------------------------------
# Function: _h_restore_path
# Automatically restore PATH when leaving scope
#------------------------------------------------------------------------
_h_restore_path() {
if [[ -n "$__H_OLD_PATH" ]]; then
PATH="$__H_OLD_PATH"
unset __H_OLD_PATH
fi
}
#------------------------------------------------------------------------
# Function: _h_completion
# Purpose : Enable tab completion for entering commands
#------------------------------------------------------------------------
_h_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local commands
trap '_h_restore_path' RETURN
_h_add_admin_paths
# Collect possible completions: aliases, functions, builtins, and executables in PATH
mapfile -t commands < <(compgen -A function -A alias -A builtin -A command -- "$cur")
# Provide them to bash-completion
COMPREPLY=("${commands[@]}")
}
#------------------------------------------------------------------------
# Function: _h_sourcedtree
# Purpose: Recursively scan for files that are sourced.
#------------------------------------------------------------------------
_h_sourcedtree() {
local file files depth max_depth
depth=0
max_depth="${MAX_DEPTH:-5}"
[[ -n "$BASH_ENV" ]] && files+=("$BASH_ENV")
# Temporarily enable nullglob
local nullglob_was=0
if ! shopt -q nullglob; then
shopt -s nullglob
nullglob_was=1
fi
if [[ -o login_shell ]]; then
[[ -d /etc/profile.d ]] && files+=( /etc/profile.d/*.sh )
[[ -f /etc/profile && -r /etc/profile ]] && files+=( /etc/profile )
if [[ -f ~/.bash_profile && -r ~/.bash_profile ]]; then
files+=( ~/.bash_profile )
elif [[ -f ~/.bash_login && -r ~/.bash_login ]]; then
files+=( ~/.bash_login )
elif [[ -f ~/.profile && -r ~/.profile ]]; then
files+=( ~/.profile )
fi
else
# Non-login interactive shell
[[ -d /etc/bash.bashrc.d ]] && files+=( /etc/bash.bashrc.d/*.sh )
[[ -f ~/.bashrc && -r ~/.bashrc ]] && files+=( ~/.bashrc )
[[ -f /etc/bash.bashrc && -r /etc/bash.bashrc ]] && files+=( /etc/bash.bashrc )
[[ -f /etc/bashrc && -r /etc/bashrc ]] && files+=( /etc/bashrc )
if (( "$__H_RHEL_like" == 1 )); then
# This system is Fedora/RHEL-like
files+=( /etc/profile.d/*.sh )
fi
fi
# Restore nullglob if we changed it
(( nullglob_was == 1 )) && shopt -u nullglob
for file in "${files[@]}"; do
_h_sourcedtree_single "$file" "$depth" "$max_depth"
done
}
#-----------------------------------------------------------
# Internal recursive function
_h_sourcedtree_single() {
local file="$1"
local depth="${2:-0}"
local max_depth="${3:-5}"
local expanded line f left right decl
local arr_name="${BASH_REMATCH[1]}"
(( depth > max_depth )) && return
# Expand path
expanded=$(_h_expand_path "$file")
expanded="${expanded%%$'\n'}" # strip newlines
# Skip empty, duplicates, or unreadable files
[[ -z "$expanded" ]] && return
[[ -n ${__H_SOURCED_FILES_MAP["$expanded"]} ]] && return
[[ ! -f "$expanded" || ! -r "$expanded" ]] && return
__H_SOURCED_FILES_MAP["$expanded"]=1
__H_SOURCED_FILES_LIST+=("$expanded")
while IFS= read -r line; do
# Skip comments and empty lines
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
# Standard source/dot
if [[ $line =~ ^[[:space:]]*(source|\.)[[:space:]]+(.+) ]]; then
for f in ${BASH_REMATCH[2]}; do
f=$(_h_expand_path "$f")
[[ -f "$f" ]] && _h_sourcedtree_single "$f" $((depth + 1)) "$max_depth"
done
continue
fi
# Conditional: [[ -f FILE ]] && source FILE
if [[ $line == *"&&"* ]]; then
left=${line%%&&*}
right=${line#*&&}
# Remove leading/trailing spaces
left=${left##*( )}
left=${left%%*( )}
right=${right##*( )}
right=${right%%*( )}
# Check if left is [[ -f FILE ]] and right is source FILE
if [[ $left =~ \[\[[[:space:]]*-f[[:space:]]+([^]]+)\]\] ]] && [[ $right =~ ^source[[:space:]]+(.+) ]]; then
f=$(_h_expand_path "${BASH_REMATCH[1]}")
[[ -f "$f" ]] && _h_sourcedtree_single "$f" $((depth + 1)) "$max_depth"
fi
continue
fi
# For loops: for VAR in FILES; do source $VAR; done
if [[ $line =~ ^[[:space:]]*for[[:space:]]+[a-zA-Z_][a-zA-Z0-9_]*[[:space:]]+in[[:space:]]+(.+) ]]; then
for f in ${BASH_REMATCH[1]}; do
f=$(_h_expand_path "$f")
[[ -f "$f" ]] && _h_sourcedtree_single "$f" $((depth + 1)) "$max_depth"
done
continue
fi
# Array sourcing: source "${ARRAY[@]}" (safe mode, no eval)
if [[ $line =~ source[[:space:]]+\"\$\{([a-zA-Z_][a-zA-Z0-9_]*)\[@\]\}\" ]]; then
# Extract array declaration safely
decl=$(declare -p "$arr_name" 2>/dev/null) || return
# Only allow indexed or associative arrays
[[ $decl =~ ^declare\ -[aA] ]] || return
# Extract elements (still text, not executed)
local elems
mapfile -t elems < <(
sed -n 's/^declare \-[aA][^=]*=(//p' <<<"$decl" |
tr -d '()' |
tr ' ' '\n'
)
for f in "${elems[@]}"; do
# Reject anything remotely executable
[[ $f =~ [\$\`\;\&\|] ]] && continue
f=$(_h_expand_path "$f")
[[ -f "$f" ]] && _h_sourcedtree_single "$f" $((depth + 1)) "$max_depth"
done
fi
done < "$expanded"
}
#-----------------------------------------------------------
# Helper: _h_expand_path
_h_expand_path() {
local p="$1"
# Strip quotes, semicolons, leading/trailing spaces
p="${p//\"/}"
p="${p//\'/}"
p="${p//;/}"
p="${p##*( )}"
p="${p%%*( )}"
# Tilde expansion
[[ "$p" == "~"* ]] && p="${p/#\~/$HOME}"
# Replace known environment variables
[[ -n "$HOME" ]] && p="${p//\$HOME/$HOME}"
[[ -n "$BASH_ENV" ]] && p="${p//\$BASH_ENV/$BASH_ENV}"
# Convert to absolute path if possible
if command -v realpath &>/dev/null && [[ -e "$p" ]]; then
p=$(realpath "$p" 2>/dev/null || echo "$p")
fi
# Remove newlines and trailing spaces
p="${p//$'\n'/}"
p="${p%%*( )}"
printf '%s' "$p"
}
#------------------------------------------------------------------------
# Function: _h_print_trace
# Purpose: Command Resolution Trace (aliases, functions, builtins, PATH)
#------------------------------------------------------------------------
_h_print_trace() {
local cmd="$1"
local path_winner=0
local bash_winner_type=""
local -a res state rc
local winner=""
local found_path=""
local alias_def="" file line canonical interp ctype
local shadowed_file=0
state=""
ctype=$(type -t -- "$cmd" 2>/dev/null)
if [[ -z "$ctype" ]]; then
printf "├─ ${RED}Unknown or invalid command: ${CYAN}%s${RESET}\n" "$cmd"
printf " ↳ Check your spelling and try again\n\n"
return 1
fi
_h_resolve_command "$cmd" res
printf "├─ Command Resolution Trace of ${CYAN}%s${RESET}\n" "$cmd"
printf " ⎟ \n"
# 1. Alias
if [[ ${res[0]} == alias\|found* ]]; then
alias_def="${res[0]#*|found|}"
printf " ├─ Alias: - ${CYAN}found %s → %s${RESET}\n" "$cmd" "$alias_def"
winner="alias"
bash_winner_type="alias"
found_path="$cmd"
else
printf " ├─ Alias: - not found\n"
fi
# 2. function
if [[ ${res[1]} == function\|found* ]]; then
IFS='|' read -r _ _ file line <<< "${res[1]}"
if [[ -z $winner ]]; then
winner="function"
bash_winner_type="function"
found_path="$cmd"
printf " ├─ Function: - ${CYAN}found %s → (%s : line %s)${RESET}\n" "$cmd" "$file" "$line"
else
printf " ├─ Function: - ${GREY}found %s → (%s : line %s) [shadowed]${RESET}\n" "$cmd" "$file" "$line"
fi
else
printf " ├─ Function: - not found\n"
fi
# 3. Builtin
if [[ ${res[2]} == builtin\|found ]]; then
_h_is_builtin_disabled "$cmd"
rc=$?
[[ $rc -eq 0 ]] && state2=disabled
[[ $rc -eq 1 ]] && state2=enabled
if [[ -z $winner ]]; then
printf " ├─ Builtin: - ${CYAN}%s → %s${RESET}\n" "$cmd" "$state2"
winner="builtin"
bash_winner_type="builtin"
[[ -z $found_path ]] && found_path="$cmd"
else
# builtin shadowed by alias or function
printf " ├─ Builtin: - ${GREY}%s → %s [shadowed]${RESET}\n" "$cmd" "$state2"
fi
else
printf " ├─ Builtin: - not found\n"
fi
# 4. Keyword
if [[ ${res[3]} == keyword\|found ]]; then
if [[ -z $winner ]]; then
printf " ├─ Keyword: - ${CYAN}%s → found${RESET}\n" "$cmd"
winner="keyword"
bash_winner_type="keyword"
[[ -z $found_path ]] && found_path="$cmd"
else
printf " ├─ Keyword: - ${GREY}%s → found [shadowed]${RESET}\n" "$cmd"
fi
else
printf " ├─ Keyword: - not found\n"
fi
printf " ⎟ \n"
# 5. PATH
printf " ├─ \$PATH in order:\n"
for ((i=4; i<${#res[@]}; i++)); do
IFS='|' read -r _ dir state target <<< "${res[i]}"
case "$state" in
notfound)
printf " ⎟ ↳ %-24s - not found\n" "$dir"
;;
file)
if [[ -z $found_path ]]; then
printf " ⎟ ↳ %-24s - ${CYAN}%s${RESET} - ${CYAN}found${RESET}\n" "$dir" "$cmd"
found_path="$dir/$cmd"
[[ -z $bash_winner_type ]] && path_winner=1
else
printf " ⎟ ↳ %-24s - ${GREY}%s${RESET} - ${GREY}found [shadowed]${RESET}\n" "$dir" "$cmd"
fi
;;
symlink)
if [[ -z $found_path ]]; then
printf " ⎟ ↳ %-24s - ${CYAN}%s${RESET} - ${YELLOW}Symlink to [ %s ]${RESET}\n" \
"$dir" "$cmd" "$target"
found_path="$dir/$cmd"
[[ -z $bash_winner_type ]] && path_winner=1
else
printf " ⎟ ↳ %-24s - ${GREY}%s${RESET} - ${GREY}Symlink [shadowed]${RESET}\n" "$dir" "$cmd"
fi
;;
esac
done
printf " ⎟ \n"
# Determine if any PATH entry exists for this cmd
for ((i=4; i<${#res[@]}; i++)); do
IFS='|' read -r _ dir state target <<< "${res[i]}"
if [[ "$state" == "file" || "$state" == "symlink" ]]; then
shadowed_file=1
break
fi
done
# Bash resolution target
printf " ├─ Bash Resolution Target:\n"
if [[ -n $found_path ]]; then
canonical=$(readlink -f -- "$found_path" 2>/dev/null || echo "$found_path")
case "$bash_winner_type" in
alias)
printf " ⎟ ↳ Executed: ${CYAN}%s${RESET}\n" "$alias_def"
;;
function)
printf " ⎟ ↳ Executed: ${CYAN}Function %s → (%s : line %s)${RESET}\n" "$found_path" "$file" "$line"
;;
builtin)
if [[ "$state2" == "enabled" ]]; then
printf " ⎟ ↳ Executed: ${CYAN}Builtin %s → %s ${RESET}\n" "$found_path" "$state2"
else
printf " ⎟ ↳ Executed: ${RED}Builtin %s is %s → Nothing Executed${RESET}\n" "$found_path" "$state2"
fi
;;
keyword)
# Always print keyword line
printf " ⎟ ↳ Resolved Keyword: ${CYAN}%s${RESET}\n" "$cmd"
if (( shadowed_file )); then
printf " ⎟ ↳ Note: filesystem executables named ${CYAN}%s${RESET} are unreachable by bare invocation\n" "$cmd"
fi
;;
*)
if [[ "$found_path" != "$canonical" ]]; then
printf " ⎟ ↳ Executed: ${CYAN}%s${RESET} - ${YELLOW}Symlink to [ %s ]${RESET}\n" "$found_path" "$canonical"
else
printf " ⎟ ↳ Executed: ${CYAN}%s${RESET}\n" "$found_path"
fi
;;
esac
else
printf " ⎟ ↳ Executed: not found\n"
fi
printf " ⎟ \n"
printf " ├─ Kernel Execution Target:\n"
# Kernel execution
if (( path_winner )); then
canonical=$(readlink -f -- "$found_path" 2>/dev/null || echo "$found_path")
interp=$(readelf -l "$canonical" 2>/dev/null | awk '/interpreter/ {gsub(/[][]/, "", $NF); print $NF}')
if [[ "$found_path" != "$canonical" ]]; then
printf " ⎟ ↳ ${YELLOW}Symlink${RESET} → ${BPURP}%s${RESET}\n" "$canonical"
else
printf " ⎟ ↳ Executable → %s\n" "$canonical"
fi
# ELF interpreter
if file "$canonical" 2>/dev/null | grep -q ELF; then
[[ -n $interp ]] && printf " ⎟ ↳ ELF interpreter: ${CYAN}%s${RESET}\n" "$interp"
fi
# Script shebang
if head -1 "$canonical" 2>/dev/null | grep -q '^#!'; then
printf " ⎟ ↳ Shebang: ${CYAN}%s${RESET}\n" "$(head -1 "$canonical" | cut -c3-)"
fi
else
printf " ⎟ ↳ NONE \n"
fi
printf " ⎟ \n"
printf " └──────────────────────────────────────────\n\n"
}
#---------------------
# Helper function: _h_resolve_command
_h_resolve_command() {
local cmd="$1"
local -n out_refh="$2"
local type_kind line file
local was_extdebug=0
out_refh=()
type_kind=$(type -t "$cmd" 2>/dev/null)
# Alias
if [[ "$type_kind" == "alias" ]]; then
out_refh+=("alias|found|$(alias "$cmd")")
else
out_refh+=("alias|notfound")
fi
# Function
if declare -F "$cmd" &>/dev/null; then
shopt -q extdebug || { shopt -s extdebug; was_extdebug=1; }
read -r _ line file <<< "$(declare -F "$cmd")"
(( was_extdebug )) && shopt -u extdebug
[[ -z $file ]] && file="interactive shell"
out_refh+=("function|found|$file|$line")
else
out_refh+=("function|notfound")
fi
# Builtin
if compgen -b | grep -qx "$cmd"; then
out_refh+=("builtin|found")
else
out_refh+=("builtin|notfound")
fi
# Keyword
if compgen -k | grep -qx "$cmd"; then
out_refh+=("keyword|found")
else
out_refh+=("keyword|notfound")
fi
# PATH
IFS=: read -ra dirs <<< "$PATH"
for d in "${dirs[@]}"; do
local p="$d/$cmd"
if [[ -x "$p" ]]; then
if [[ -L "$p" ]]; then