-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path.bash_ct
More file actions
1796 lines (1538 loc) · 60.6 KB
/
.bash_ct
File metadata and controls
1796 lines (1538 loc) · 60.6 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
#-----------------------------------------------------------------------------------------------
# Command Trace aka ct
# Purpose: Analyzes a Bash command, alias, builtin, keyword, function, or binary
# Trace command resolution, with shadowed command detection.
#-----------------------------------------------------------------------------------------------
# Copyright (c) 2025-2026 John Blair
# Licensed under the MIT License. See LICENSE file for details.
#-----------------------------------------------------------------------------------------------
# BEHAVIORAL NOTES:
#
# • This script is intended to be SOURCED into an interactive Bash shell.
# • This script does NOT use `set -euo pipefail`.
# • PATH is may be extended during execution to improve discovery of
# administrative and user-level command locations. PATH is restored on exit.
#
# • Shell option `extglob` may be enabled temporarily and is restored afterward.
#
# • Kernel-level inspection may occur for PATH executables, including:
# - symlink resolution
# - ELF interpreter detection
# - shebang parsing
# - alternatives system detection
#
# • Bare command names only.
# Paths (e.g. /bin/ls) are rejected.
#-----------------------------------------------------------------------------------------------
# AUTO-EXTENDED DISCOVERY (JSON: auto_extended)
#
# When ct is invoked without -x/--extend and a command is not
# found in the user's PATH, ct will temporarily include known
# administrative paths (e.g. /usr/sbin, /sbin) to locate it.
#
# This behavior:
# • does NOT modify PATH permanently
# • does NOT execute the command
# • is intended for interactive discovery
#
# When auto-extension occurs, JSON output includes:
#
# "auto_extended": true
#
# Explicit -x/--extend disables auto-extension semantics and
# guarantees exhaustive analysis regardless of resolution.
#-----------------------------------------------------------------------------------------------
if [[ -z "${BASH_VERSION:-}" ]]; then
printf "ct must be sourced or executed by bash.\n" >&2
return 1
fi
__CT_version=4.3.0
__CT_needed_deps=(grep file cut head readlink readelf awk)
__CT_optional_deps=(tput)
__CT_extglob_was=0
mapfile -t __CT_KEYWORDS < <(compgen -k)
mapfile -t __CT_BUILTINS < <(compgen -b)
complete -F _ct_completion ct
#------------------------------------------------------------------------
# Function: ct
# Purpose : User-facing entry point.
#
# Behavior:
# • Parses command-line options
# • Rejects path-based input
# • Dispatches to human-readable or JSON output
#
# Exit codes:
# • 0 → successful resolution
# • 1 → command not found or invalid input
#------------------------------------------------------------------------
ct() {
local __CT_JSON_OUTPUT=0
local __CT_EXTEND_PATH=0
local __CT_AUTO_EXTEND=0
local __CT_CONFLICT=0
trap '_ct_exit' RETURN
while [[ $# -gt 0 ]]; do
local arg="$1"
case "$arg" in
--help)
_ct_usage
return 0
;;
--version)
_ct_ver
return 0
;;
--conflict)
__CT_CONFLICT=1
shift
;;
--json)
__CT_JSON_OUTPUT=1
shift
;;
--extend)
__CT_EXTEND_PATH=1
shift
;;
--json--extend|--extend--json)
__CT_JSON_OUTPUT=1
__CT_EXTEND_PATH=1
shift
;;
--json--conflict|--conflict--json)
__CT_JSON_OUTPUT=1
__CT_CONFLICT=1
shift
;;
-*) # short flags, possibly combined like -jx
local i
for (( i=1; i<${#arg}; i++ )); do
local flag="${arg:i:1}"
case "$flag" in
j) __CT_JSON_OUTPUT=1 ;;
x) __CT_EXTEND_PATH=1 ;;
c) __CT_CONFLICT=1 ;;
h)
_ct_usage
return 0
;;
v)
_ct_ver
return 0
;;
*)
printf "Unknown option: -%s\n" "$flag" >&2
return 1
;;
esac
done
shift
;;
*)
break # first non-option argument (command)
;;
esac
done
if [[ $__CT_CONFLICT == 1 ]]; then
_ct_conflicts "$__CT_JSON_OUTPUT" "$__CT_EXTEND_PATH"
return 0
fi
# Validate input
[[ -z "$1" ]] && _ct_usage && return 0
# Auto-extend PATH if command not found but exists in admin paths
if [[ -n "$1" && $__CT_EXTEND_PATH -eq 0 ]]; then
if ! command -v -- "$1" &>/dev/null; then
if _ct_found_in_admin_paths "$1"; then
__CT_EXTEND_PATH=1
__CT_AUTO_EXTEND=1
fi
fi
fi
# ---- Startup ----
_ct_startup "$__CT_EXTEND_PATH"
# JSON mode rejects path input
if [[ $__CT_JSON_OUTPUT == 1 ]] && [[ "$1" == */* ]]; then
local path_type
if [[ -d "$1" ]]; then
path_type="directory"
elif [[ -f "$1" ]]; then
path_type="file"
else
path_type=""
fi
if [[ -n $path_type ]]; then
printf '{ "error": true, "type": "invalid_input", "message": "%s is a %s. Command Trace only works with bare command names." }\n' "$1" "$path_type"
else
printf '{ "error": true, "type": "invalid_input", "message": "Unknown or invalid command: %s" }\n' "$1"
return 1
fi
return 1
fi
# Human-readable mode rejects path input with explanation
if [[ "$1" == */* ]]; then
if [[ -d "$1" ]]; then
printf "├─ ${__CT_RED}%s is a directory${__CT_RESET}\n" "$1"
printf " ↳ Please provide the command name only, not a path.\n\n"
return 1
elif [[ -f "$1" ]]; then
printf "├─ ${__CT_RED}%s is a file${__CT_RESET}\n" "$1"
printf " ↳ Command Trace only works with bare command names.\n\n"
return 1
fi
fi
# Dispatch output
if (( __CT_JSON_OUTPUT )); then
_ct_json_output "$1"
else
_ct_print_trace "$1"
fi
}
#------------------------------------------------------------------------
# Function: _ct_resolve
# Purpose : Core command resolution engine.
#
# Inputs:
# $1 → command name (bare token, no path)
# $2 → nameref to associative array for resolution results (RES)
# $3 → nameref to indexed array for PATH scan results (PATH_ENTRIES)
#
# Outputs (RES associative array):
# command → original command string
# bash_type → alias|function|keyword|builtin|path|notfound
# shadowed_fs → true if filesystem executables are unreachable
#
# alias_* → alias detection and definition
# function_* → function location and line
# builtin_* → builtin state (enabled/disabled)
# keyword_found → keyword match
#
# kernel_* → execution target details (PATH only)
#
# Notes:
# • Resolution precedence follows Bash rules, not filesystem order.
# • PATH scanning records *all* candidates, not just the winner.
#------------------------------------------------------------------------
# shellcheck disable=SC2154
_ct_resolve() {
__CT_POSIX_SPECIAL_BUILTINS=(
:
.
break
continue
eval
exec
exit
export
readonly
return
set
shift
times
trap
unset
)
local cmd="$1"
local -n R="$2" # associative result
local -n P="$3" # indexed PATH entries
local alias_out
# shellcheck disable=SC2034
R=()
P=()
R[command]="$cmd"
R[bash_type]="notfound"
R[shadowed_fs]=false
R[function_shadowed]=false
R[builtin_shadowed]=false
R[keyword_shadowed_alias]=false
R[alias_shadowed]=false
R[posix_mode]=false
# ------------------------------------------------------------
# Edge cases
# ------------------------------------------------------------
case "$cmd" in
'{'|'}'|'('|')'|'[['|']]'|']'|'.')
R[keyword_found]=true
R[bash_type]="keyword"
;;
esac
# ------------------------------------------------------------
# Alias
# ------------------------------------------------------------
if alias "$cmd" &>/dev/null; then
alias_out=$(alias -- "$cmd" 2>/dev/null) || return
R[alias_found]=true
R[alias_def]="$alias_out"
R[bash_type]="alias"
else
R[alias_found]=false
fi
# ------------------------------------------------------------
# POSIX special builtin (pre-function precedence)
# ------------------------------------------------------------
if (( __CT_POSIX_MODE )) && _ct_cache_compgen "$cmd" __CT_BUILTINS; then
if _ct_is_posix_special_builtin "$cmd"; then
R[builtin_found]=true
R[posix_special]=true
fi
fi
if (( __CT_POSIX_MODE )); then
R[posix_mode]=true
fi
# ------------------------------------------------------------
# Function (skip if POSIX special builtin already resolved)
# ------------------------------------------------------------
if [[ ${R[posix_special]} != true ]] && declare -F "$cmd" &>/dev/null; then
R[function_found]=true
local line file
shopt -q extdebug || { shopt -s extdebug; local _ext=1; }
read -r _ line file <<<"$(declare -F "$cmd")"
[[ $_ext ]] && shopt -u extdebug
R[function_file]="${file:-interactive shell}"
R[function_line]="$line"
# Mark shadowed if higher precedence exists (alias or keyword)
if [[ ${R[bash_type]} =~ ^(alias|keyword|builtin)$ ]]; then
R[function_shadowed]=true
else
R[bash_type]="function"
R[function_shadowed]=false
fi
else
R[function_found]=false
fi
# ------------------------------------------------------------
# Keyword (higher precedence than builtin)
# ------------------------------------------------------------
if _ct_cache_compgen "$cmd" __CT_KEYWORDS; then
R[keyword_found]=true
R[bash_type]="keyword"
else
R[keyword_found]=false
fi
if [[ ${R[keyword_found]} == true && ${R[alias_found]} == true ]]; then
R[keyword_shadowed_alias]=true
fi
# ------------------------------------------------------------
# Builtin
# ------------------------------------------------------------
if _ct_cache_compgen "$cmd" __CT_BUILTINS; then
R[builtin_found]=true
# enabled/disabled state
if enable -n | grep -Fxq -- "enable -n $cmd"; then
R[builtin_state]="disabled"
else
R[builtin_state]="enabled"
fi
# shadowed only if enabled and something higher-precedence exists
if [[ ${R[builtin_state]} == "enabled" && \
${R[bash_type]} =~ ^(alias|function|keyword)$ && \
( "$__CT_POSIX_MODE" -eq 0 || ! $(_ct_is_posix_special_builtin "$cmd") ) ]]; then
R[builtin_shadowed]=true
fi
# builtin wins only if enabled and not shadowed, and nothing else resolved yet
if [[ ${R[builtin_state]} == "enabled" && ${R[builtin_shadowed]} == false && ${R[bash_type]} == "notfound" ]]; then
R[bash_type]="builtin"
R[bash_winner]="$cmd"
fi
else
R[builtin_found]=false
R[builtin_state]=null
R[builtin_shadowed]=false
fi
# ------------------------------------------------------------
# POSIX special builtin precedence
# ------------------------------------------------------------
if (( __CT_POSIX_MODE )) && _ct_cache_compgen "$cmd" __CT_BUILTINS; then
if _ct_is_posix_special_builtin "$cmd"; then
R[builtin_found]=true
# POSIX special builtin shadows function
if [[ ${R[function_found]} == true ]]; then
R[function_shadowed]=true
fi
fi
fi
# Builtin only wins if no higher-precedence Bash entity already resolved
if [[ ${R[builtin_found]} == true &&
${R[builtin_state]} == "enabled" &&
${R[builtin_shadowed]} == false &&
${R[bash_type]} == "notfound" ]]; then
R[bash_type]="builtin"
R[bash_winner]="$cmd"
fi
# ------------------------------------------------------------
# PATH scan
# PATH entry encoding format (PATH_ENTRIES):
# "dir|state|target|shadow"
#
# dir → PATH directory
# state → notfound | file | symlink
# target → resolved target (for symlink), empty otherwise
# shadow → true if this entry is unreachable by bare invocation
# ------------------------------------------------------------
local found_path=""
local path_winner_seen=0
IFS=: read -ra _dirs <<<"$PATH"
for d in "${_dirs[@]}"; do
local p="$d/$cmd"
# Skip if not executable
if [[ ! -x "$p" ]]; then
P+=("$d|notfound||false")
continue
fi
local state=file target="$p"
if [[ -L "$p" ]]; then
state=symlink
target="$(readlink "$p")"
fi
local shadow=false
# Mark as shadowed if a higher-priority Bash resolution exists
if [[ ${R[bash_type]} =~ ^(alias|function|builtin|keyword)$ ]]; then
shadow=true
R[shadowed_fs]=true
elif (( path_winner_seen )); then
shadow=true
else
path_winner_seen=1
# Only set bash_type=path if no higher-priority type is set
[[ ${R[bash_type]} == "notfound" ]] && R[bash_type]="path"
found_path="$p"
fi
P+=("$d|$state|$target|$shadow")
done
# ------------------------------------------------------------
# Kernel execution details + alternatives detection
# ------------------------------------------------------------
if [[ ${R[bash_type]} == "path" && -n $found_path ]]; then
R[kernel_path]="$found_path"
R[kernel_canonical]="$(readlink -f "$found_path")"
R[elf_interp]=""
R[shebang]=""
# ELF interpreter (if ELF binary)
if file "${R[kernel_canonical]}" 2>/dev/null | grep -q ELF; then
R[elf_interp]="$(readelf -l "${R[kernel_canonical]}" 2>/dev/null \
| awk '/interpreter/ {gsub(/[][]/, "", $NF); print $NF}')"
fi
# Shebang (if script)
if head -1 "${R[kernel_canonical]}" 2>/dev/null | grep -q '^#!'; then
R[shebang]="$(head -1 "${R[kernel_canonical]}" | cut -c3-)"
fi
# Symlink chain (safe string for JSON)
local chain=()
local x="$found_path"
while [[ -L "$x" ]]; do
local y
y="$(readlink "$x")"
chain+=("$x -> $y")
x="$y"
done
R[kernel_chain]=$(printf '%s\n' "${chain[@]}") # newline-delimited string
# Alternatives detection
R[alternatives]=false
R[alternatives_link]=null
R[alternatives_target]=null
x="$found_path"
while [[ -L "$x" ]]; do
if [[ "$x" == /etc/alternatives/* ]]; then
R[alternatives]=true
R[alternatives_link]="$x"
R[alternatives_target]="$(readlink -f "$x")"
break
fi
x="$(readlink -f "$x")"
done
fi
# special edge case
if [[ $cmd == "." ]]; then
R[bash_type]="keyword"
R[keyword_found]=true
R[builtin_shadowed]=false
fi
: "${R[bash_type]:=notfound}"
return 0
}
#------------------------------------------------------------------------
# Function: _ct_cache_compgen "$cmd" __CT_KEYWORDS
# Purpose: avoid abusing compgen for a report mode (multiple commands at once)
#------------------------------------------------------------------------
_ct_cache_compgen() {
local needle="$1"
local -n haystack="$2"
local item
for item in "${haystack[@]}"; do
[[ "$item" == "$needle" ]] && return 0
done
return 1
}
#------------------------------------------------------------------------
# Function: _ct_is_posix_special_builtin
# Purpose: check if command is a posix special builtin
#------------------------------------------------------------------------
_ct_is_posix_special_builtin() {
local b
for b in "${__CT_POSIX_SPECIAL_BUILTINS[@]}"; do
[[ $b == "$1" ]] && return 0
done
return 1
}
#------------------------------------------------------------------------
# Function: _ct_found_in_admin_paths
# Purpose: check if command exists outside of user path
#------------------------------------------------------------------------
_ct_found_in_admin_paths() {
local cmd="$1"
local d
local _CT_ADMIN_PATHS=(
"/flatpak/bin"
"/snap/bin"
"/usr/local/sbin"
"/usr/sbin"
"/sbin"
"/opt/sbin"
)
for d in "${_CT_ADMIN_PATHS[@]}"; do
[[ -x "$d/$cmd" && -f "$d/$cmd" ]] && return 0
done
return 1
}
#------------------------------------------------------------------------
# Function: _ct_print_trace
# Purpose: Command Resolution Trace human display
#------------------------------------------------------------------------
# Human Output:
#
# • "Bash Resolution Target"
# What Bash resolves the command to, based on shell semantics.
#
# • "Kernel Execution Target"
# What the kernel actually executes (filesystem path, interpreter).
#
# These are intentionally separated to highlight shadowing and indirection.
#------------------------------------------------------------------------
_ct_print_trace() {
local cmd="$1"
declare -A RES
declare -a PATH_ENTRIES
_ct_resolve "$cmd" RES PATH_ENTRIES || return 1
if [[ ${RES[bash_type]} == "notfound" ]]; then
printf "${__CT_RED}Unknown or invalid command: ${__CT_CYAN}%s${__CT_RESET}\n" "$cmd"
printf " ↳ Check your spelling and try again\n\n"
return 1
fi
printf "Command Trace of ${__CT_CYAN}%s${__CT_RESET}\n" "$cmd"
if (( __CT_AUTO_EXTEND )); then
printf "\n"
printf "Not in \$USER \$PATH\nFound in system \$PATH %s(auto-extended)%s:\n" "${__CT_YELLOW}" "${__CT_RESET}"
fi
# Dispatch output
if (( __CT_POSIX_MODE )); then
printf "\n"
printf "Bash is in POSIX mode:\nPOSIX special builtins cannot be shadowed by functions;\nconflicting function names are disallowed.\n"
# printf "The shell will not execute a function whose name contains one or more slashes.\n"
fi
printf "\n"
# ------------------------------------------------------------
# Keyword
# ------------------------------------------------------------
if [[ ${RES[keyword_found]} == true ]]; then
printf "Keyword: - ${__CT_CYAN}%s → found${__CT_RESET}\n" "$cmd"
else
printf "Keyword: - not found\n"
fi
# ------------------------------------------------------------
# Alias
# ------------------------------------------------------------
if [[ ${RES[alias_found]} == true ]]; then
printf "Alias: - ${__CT_CYAN}%s → found → %s${__CT_RESET}\n" "$cmd" "${RES[alias_def]}"
else
printf "Alias: - not found\n"
fi
# ------------------------------------------------------------
# Function
# ------------------------------------------------------------
if [[ ${RES[function_found]} == true ]]; then
if [[ ${RES[function_shadowed]} == true ]]; then
printf "Function: - ${__CT_GREY}%s → found → Function %s (%s : line %s) [shadowed]${__CT_RESET}\n" \
"$cmd" "$cmd" "${RES[function_file]}" "${RES[function_line]}"
else
printf "Function: - ${__CT_CYAN}%s → found → Function %s (%s : line %s)${__CT_RESET}\n" \
"$cmd" "$cmd" "${RES[function_file]}" "${RES[function_line]}"
fi
else
printf "Function: - not found\n"
fi
# ------------------------------------------------------------
# Builtin
# ------------------------------------------------------------
if [[ ${RES[builtin_found]} == true ]]; then
if [[ ${RES[builtin_state]} == "enabled" ]]; then
if [[ ${RES[builtin_shadowed]} == true ]]; then
printf "Builtin: - ${__CT_GREY}%s → found → %s [shadowed]${__CT_RESET}\n" \
"$cmd" "${RES[builtin_state]}"
else
printf "Builtin: - ${__CT_CYAN}%s → found → %s${__CT_RESET}\n" \
"$cmd" "${RES[builtin_state]}"
fi
else
printf "Builtin: - ${__CT_GREY}%s → found → %s${__CT_RESET}\n" \
"$cmd" "${RES[builtin_state]}"
fi
else
printf "Builtin: - not found\n"
fi
printf "\n"
# ------------------------------------------------------------
# PATH scan rendering
#
# Shows every PATH entry in order, not just the winner.
# Shadowed entries indicate commands that exist but cannot
# be reached via bare invocation.
# ------------------------------------------------------------
printf "\$PATH in order:\n"
for entry in "${PATH_ENTRIES[@]}"; do
IFS='|' read -r dir state target shadow <<<"$entry"
local usr_merged=""
# Detect usr-merged directories by comparing inode to kernel_path
if [[ -n "${RES[kernel_path]}" && -e "$dir/$cmd" ]]; then
local inode1 inode2
inode1=$(stat -c %i "$dir/$cmd" 2>/dev/null || echo "")
inode2=$(stat -c %i "${RES[kernel_path]}" 2>/dev/null || echo "")
[[ "$inode1" == "$inode2" && "$dir/$cmd" != "${RES[kernel_path]}" ]] && usr_merged=" [usr-merged]"
fi
case "$state" in
notfound)
printf " ↳ %-24s - not found\n" "$dir"
;;
file)
if [[ $shadow == true ]]; then
printf " ↳ %-24s - ${__CT_GREY}%s [shadowed]%s${__CT_RESET}\n" "$dir" "$cmd" "$usr_merged"
else
printf " ↳ %-24s - ${__CT_CYAN}%s found${__CT_RESET}%s\n" "$dir" "$cmd" "$usr_merged"
fi
;;
symlink)
if [[ $shadow == true ]]; then
printf " ↳ %-24s - ${__CT_GREY}%s (symlink) [shadowed]%s${__CT_RESET}\n" "$dir" "$cmd" "$usr_merged"
else
printf " ↳ %-24s - ${__CT_CYAN}%s${__CT_RESET} → ${__CT_YELLOW}%s${__CT_RESET}%s\n" \
"$dir" "$cmd" "$target" "$usr_merged"
fi
;;
esac
done
printf "\n"
# ------------------------------------------------------------
# Bash resolution target
# ------------------------------------------------------------
printf "Bash Resolution Target:\n"
case "${RES[bash_type]}" in
keyword) winner_display="${__CT_CYAN}Keyword → ${RES[command]}${__CT_RESET}" ;;
alias) winner_display="${__CT_CYAN}Alias → ${RES[command]} → ${RES[alias_def]}${__CT_RESET}" ;;
function) winner_display="${__CT_CYAN}Function → ${RES[command]} → ${RES[function_file]} : line ${RES[function_line]}${__CT_RESET}" ;;
builtin) winner_display="${__CT_CYAN}Builtin → ${RES[command]} → ${RES[builtin_state]}${__CT_RESET}" ;;
path) winner_display="${__CT_CYAN}Filesystem → ${RES[kernel_path]}${__CT_RESET}" ;;
*) printf "not found\n" ;;
esac
printf " ↳ Resolved to: %s\n" "$winner_display"
# Check for secondary entity if keyword won and a shadowed alias or builtin exists
if [[ "${RES[bash_type]}" == "keyword" ]]; then
if [[ ${RES[alias_found]} == true ]]; then
printf " ↳ And: ${__CT_CYAN}Alias → %s${__CT_RESET}\n" "${RES[alias_def]}"
fi
if [[ ${RES[builtin_state]} == "enabled" ]]; then
printf " ↳ And: ${__CT_CYAN}Builtin → %s → %s${__CT_RESET}\n" "${RES[command]}" "${RES[builtin_state]}"
elif [[ ${RES[builtin_state]} == "disabled" ]]; then
printf " ↳ And: ${__CT_GREY}Builtin → %s → %s${__CT_RESET}\n" "${RES[command]}" "${RES[builtin_state]}"
printf " ↳ Note: Builtin implementation is disabled; execution will fail.\n"
fi
if [[ ${RES[alias_found]} == true || ${RES[function_found]} == true || ${RES[path_found]} == true ]]; then
printf " ↳ Note: Keyword ${__CT_CYAN}'%s'${__CT_RESET} always wins in its reserved context; other commands are ignored.\n" \
"${RES[command]}"
fi
fi
if [[ ${RES[function_found]} == true && ${RES[function_shadowed]} == true ]]; then
printf " ↳ Note: Function ${__CT_CYAN}'%s'${__CT_RESET} is unreachable by bare invocation.\n" "$cmd"
fi
if [[ ${RES[builtin_found]} == true && ${RES[builtin_shadowed]} == true ]]; then
printf " ↳ Note: Builtin ${__CT_CYAN}'%s'${__CT_RESET} is unreachable by bare invocation.\n" "$cmd"
fi
# Only print shadowed note for non-builtin
if [[ ${RES[shadowed_fs]} == true ]]; then
printf " ↳ Note: Filesystem executables named ${__CT_CYAN}'%s'${__CT_RESET} are unreachable by bare invocation.\n" "$cmd"
fi
printf "\n"
# ------------------------------------------------------------
# Kernel execution target
#
# Only applies when bash_type == path.
# ------------------------------------------------------------
printf "Kernel Execution Target:\n"
if [[ ${RES[bash_type]} == path ]]; then
if [[ "${RES[kernel_path]}" != "${RES[kernel_canonical]}" ]]; then
printf " ↳ Executable → ${__CT_BPURP}%s${__CT_RESET}\n" "${RES[kernel_canonical]}"
else
printf " ↳ Executable → ${__CT_CYAN}%s${__CT_RESET}\n" "${RES[kernel_canonical]}"
fi
[[ -n ${RES[elf_interp]} ]] && \
printf " ↳ ELF interpreter: ${__CT_CYAN}%s${__CT_RESET}\n" "${RES[elf_interp]}"
[[ -n ${RES[shebang]} ]] && \
printf " ↳ Shebang: ${__CT_CYAN}%s${__CT_RESET}\n" "${RES[shebang]}"
# symlink chain
if [[ -n ${RES[kernel_chain]} ]]; then
printf " ↳ Symlink chain:\n"
IFS=$'\n' read -r -d '' -a chain_lines <<<"${RES[kernel_chain]}" || true
local last_index=$(( ${#chain_lines[@]} - 1 ))
for i in "${!chain_lines[@]}"; do
local line="${chain_lines[i]}"
local src="${line%% -> *}"
local tgt="${line##* -> }"
if (( i == last_index )); then
# Final target (kernel executable)
printf " → ${__CT_YELLOW}%s${__CT_RESET} -> ${__CT_BPURP}%s${__CT_RESET}\n" "$src" "$tgt"
else
# intermediate symlink
printf " → ${__CT_CYAN}%s${__CT_RESET} -> ${__CT_YELLOW}%s${__CT_RESET}\n" "$src" "$tgt"
fi
done
fi
else
printf " ↳ NONE\n"
fi
printf "\n"
}
#------------------------------------------------------------------------
# Function: _ct_startup
# Purpose : One-time setup per ct invocation
#
# Ensures environment consistency and dependency availability.
#------------------------------------------------------------------------
_ct_startup() {
local __CT_EXTEND_PATH="$1"
# Save PATH if not already saved
if [[ -z "$__CT_OLD_PATH" ]]; then
__CT_OLD_PATH="$PATH"
fi
_ct_bash_posix_mode
_ct_bash_ver_check
_ct_check_dependencies __CT_needed_deps __CT_optional_deps 1 || return 1 # 1 = exit if required
(( __CT_EXTEND_PATH )) && _ct_add_admin_paths
_ct_enable_extglob
_ct_setup_colors # Setup tput or ansi
}
#------------------------------------------------------------------------
# Function: _ct_bash_posix_mode
# Purpose : Check if bash posix mode to apply posix rules if needed
#------------------------------------------------------------------------
_ct_bash_posix_mode() {
__CT_POSIX_MODE=0
shopt -qo posix && __CT_POSIX_MODE=1
}
#------------------------------------------------------------------------
# Function: _ct_exit
# Purpose : Cleanup handler
#
# Registered via trap to guarantee restoration of shell state.
#------------------------------------------------------------------------
_ct_exit() {
_ct_restore_path
__CT_RESET_extglob
__CT_edgecase=0
__CT_EXTEND_PATH=0
__CT_AUTO_EXTEND=0
__CT_POSIX_MODE=0
}
#------------------------------------------------------------------------
# Function: _ct_usage
# Purpose : Display usage information and examples for the `h` command analyzer.
#------------------------------------------------------------------------
_ct_usage() {
cat <<'EOF'
Usage:
ct [option] command
Command Trace (ct) analyzes how Bash resolves a command name
and what the kernel ultimately executes.
The command must be provided as a bare command name.
Paths such as /bin/ls or ./script are rejected.
Options:
-h, --help Show this help text
-v, --version Show version and license information
-j, --json Emit JSON output suitable for scripting
-c, --conflict Environment-wide conflict analysis
EOF
}
#------------------------------------------------------------------------
# Function: _ct_ver
# Purpose : Display version information.
#------------------------------------------------------------------------
_ct_ver() {
printf "\n ct v%s — Command Trace\n" "$__CT_version"
cat <<'EOF'
MIT License
Copyright (c) 2025-2026 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: _ct_setup_colors Colors (tput → ANSI → none)
# Purpose : make stuff pretty also safe for diff setups
#------------------------------------------------------------------------
_ct_setup_colors() {
if command -v tput &>/dev/null && [[ $(tput colors 2>/dev/null) -ge 8 ]]; then
__CT_RED=$(tput setaf 1)
__CT_GREEN=$(tput setaf 2)
__CT_CYAN=$(tput setaf 6)
__CT_YELLOW=$(tput setaf 11)
__CT_BPURP=$(tput setaf 13)
__CT_GREY=$(tput setaf 245)
__CT_RESET=$(tput sgr0)
__CT_UNLINE=$(tput smul)
__CT_STOPUNLINE=$(tput rmul)
else
__CT_RED='\033[31m'
__CT_GREEN='\033[32m'
__CT_CYAN='\033[36m'
__CT_YELLOW='\033[93m'
__CT_BPURP='\033[95m'
__CT_GREY='\033[90m'
__CT_RESET='\033[0m'
__CT_UNLINE='\033[4m'
__CT_STOPUNLINE='\033[24m'
fi
# Ensure variables are always set
: "${__CT_RED:=}"
: "${__CT_GREEN:=}"
: "${__CT_CYAN:=}"
: "${__CT_YELLOW:=}"
: "${__CT_BPURP:=}"
: "${__CT_GREY:=}"
: "${__CT_RESET:=}"
: "${__CT_UNLINE:=}"
: "${__CT_STOPUNLINE:=}"
}
#------------------------------------------------------------------------
# Function: _ct_add_admin_paths
# Purpose : Temporarily extend PATH for discovery
#
# Adds common user, admin, package-manager, and container paths.
#------------------------------------------------------------------------
_ct_add_admin_paths() {
# Save PATH if not already saved
if [[ -z "$__CT_OLD_PATH" ]]; then
__CT_OLD_PATH="$PATH"
fi
local admin_dirs=(
"/flatpak/bin"
"/snap/bin"
"/usr/local/sbin"
"/usr/sbin"
"/sbin"
"/opt/sbin"
)
for dir in "${admin_dirs[@]}"; do
[[ -d "$dir" && ":$PATH:" != *":$dir:"* ]] && PATH="$PATH:$dir"
done
}
#------------------------------------------------------------------------
# Function: _ct_restore_path
# Purpose : Automatically restore PATH when needed
#------------------------------------------------------------------------
_ct_restore_path() {
if [[ -n "$__CT_OLD_PATH" ]]; then
PATH="$__CT_OLD_PATH"
fi
}
#------------------------------------------------------------------------
# Function: _ct_completion
# Purpose : Enable tab completion for entering commands
#------------------------------------------------------------------------
# Completion Notes:
#
# • Completion temporarily extends PATH to match ct resolution behavior.
# • Results include aliases, functions, builtins, and PATH commands.
#------------------------------------------------------------------------
_ct_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local commands
local _old_path="$PATH"
_ct_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[@]}")
PATH="$_old_path"
}
#------------------------------------------------------------------------
# Function: _ct_enable_extglob / __CT_RESET_extglob