/
.bashrc
3797 lines (3392 loc) · 127 KB
/
.bashrc
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
# .bashrc
#
# Changes to this file will be overwritten by `dotfiles/install.sh`.
# Add customizations to neighboring `.bashrc.local.post` file.
#
# Install this file and neighboring dotfiles using instructions in
# https://github.com/jtmoon79/dotfiles/blob/master/install.sh
#
# The order of bash initialization files is:
# 1. .bash_profile (called by bash)
# 2. .bash_profile.local (sourced by .bash_profile near the middle)
# 3. .bashrc (sourced by .bash_profile near the end)
# 4. .bashrc.local.pre (sourced by this .bashrc near the beginning)
# 5. .bashrc.local (sourced by this .bashrc near the end; only for
# backwards-compatiblity)
# 6. .bash_aliases (sourced by this .bashrc near the end)
# 7. .bashrc.builtins.post (sourced by this .bashrc near the end)
# 8. .bashrc.local.post (sourced by this .bashrc near the end)
#
# These dotfiles are intended for anyone that has to login to many different
# Unix-based hosts very often. The `install.sh` script (URL above) is fast to
# run.
# The entire original motivation was a table of information about the host and
# to modify the `$PATH`.
# Other features like colors and command timer tracking have since been added.
#
# This file defines useful fuctions, makes very few changes. See neighboring
# files `.bashrc.builtins.post`, `.bashrc.local.pre`, and
# `.bashrc.local.post` which make shell changes.
# This file is expected to be sourced by it's companion `.bash_profile`.
# This file mostly creates new functions and private variables. These can be
# used to customize the shell in neighboring files `.bashrc.builtins.post`,
# `.bashrc.local.post`. This file does forcibly create a new prompt style.
#
# These bash dot files are mainly derived for Debian-derived Linux.
# The dotfiles attempt compatibility with other Linux, Unix, and Unix on Windows
# (cygwin, MinGW), in varying environments, back to bash 3.0.
# As such, these dot files avoid reliance on external tools like `grep`, `sed`,
# etc. because those tools vary too much (i.e. GNU vs. BSD vs. busybox tools),
# or are not available (minimal Alpine Linux, other custom Linux).
# To see exceptions to this tool independence, search for `bash_installed`.
# Also, because this attempts to support minimal and unknown environments there
# are many checks and tests of typical Unix tools before presuming to use them.
#
# Features:
# - prompt prints: timer, return code, datetime,
# table of variables (adjustable), git prompt line.
# - allows "live" modification of some prompt features
# - allows override of various features via ./.bashrc.local.pre, e.g.
# color, tables of variables, prompt parts, etc.
# - attempts sourcing of /usr/share/bash-completion/bash_completion
# - fast to install: see companion install.sh at source repository.
# - fast to update: see bash_update_dots* functions.
# - safe to use in many varying Unix environments 🤞 (see docker-tests.sh)
#
# Anti-Features:
# - not POSIX compliant!
# - presumes English-preferring user (see `locale_get`)
#
# Source at https://github.com/jtmoon79/dotfiles/blob/master
#
# (sometimes) tested against
# - bash 4.x on Linux Ubuntu 18
# - bash 4.x on Linux Debian 9
# - bash 4.x on OSX 10
# - bash 3.2 on FreeBSD 10
# - bash docker images within docker-tests.sh
#
# Excellent references for understanding bash scripting language:
# https://tiswww.case.edu/php/chet/bash/bashref.html#index-command (https://archive.vn/mRrbc)
# https://mywiki.wooledge.org/BashFAQ/ (http://archive.fo/sGtzb)
# https://fvue.nl/wiki/Bash:_Error_handling (https://archive.ph/rSl6r)
# https://misc.flogisoft.com/bash/tip_colors_and_formatting (http://archive.fo/NmIkP)
# https://shreevatsa.wordpress.com/2008/03/30/zshbash-startup-files-loading-order-bashrc-zshrc-etc/ (http://archive.fo/fktxC)
# http://www.solipsys.co.uk/new/BashInitialisationFiles.html (http://archive.ph/CUzSH)
# https://github.com/webpro/awesome-dotfiles (http://archive.fo/WuiJW)
# https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
# https://www.tldp.org/LDP/abs/html/string-manipulation.html
# https://wiki.bash-hackers.org/commands/builtin/printf (http://archive.ph/wip/jDPjC)
# https://www.shell-tips.com/bash/math-arithmetic-calculation/ (https://archive.vn/dOUw0)
# https://fvue.nl/wiki/Bash:_Error_handling (https://archive.ph/rSl6r)
#
# bash key combinations:
# https://www.howtogeek.com/howto/ubuntu/keyboard-shortcuts-for-bash-command-shell-for-ubuntu-debian-suse-redhat-linux-etc/
#
# bash source code:
# http://git.savannah.gnu.org/cgit/bash.git/tree/
#
# Chet Ramey, author of bash since 1994, home page:
# https://tiswww.case.edu/php/chet/ (https://archive.ph/X1LGq)
#
# XXX: bash <4.2 cannot declare empty arrays via "empty array" syntax
#
# $ array=()
#
# bash <4.2 interprets that as a subshell invocation.
# To be backward-compatible, arrays are declared like
#
# $ array[0]=
# $ unset array[0]
#
# XXX: `declare -g` is not recognized by bash <=4.1.
#
# XXX: there would be more readonly variables but that causes difficulties
# if this .bashrc is read for an additional time. Declaring an already
# existing `readonly` variable is an error. Some tedium is necessary to do
# so without an error. This file refrains from use of `readonly`.
#
# TODO: allow more selection of colors for various parts of the prompt
# e.g $color_prompt_user $color_prompt_table $color_prompt_hostname
# $color_prompt_path $color_prompt_table_row1 $color_prompt_table_row2
# $color_prompt_table_cell_err
#
# TODO: add flock to only allow one startup of .bashrc at a time
# prevents rare case of multiple bash windows using the same tty
# which can happen when launching multiple windows, like with `terminator`
#
# BUG: prompt timer will be 0 if a command is run in a subshell, e.g.
#
# $ (sleep 3)
#
# results in next prompt with:
#
# ... last command 0s ...
#
# TODO: consider creating a `help` or similar alias that will dump information
# and provide extended examples.
#
# TODO: move these bash files to new sub-directory in dotfiles project
#
# TODO: add link to source repo in intro https://github.com/jtmoon79/dotfiles
#
# If not running interactively, do not do anything
case "$-" in
*i*)
;;
*)
if [[ "true" = "${__bashrc_FORCE_INTERACTIVE-}" ]]; then
echo 'Warning: Forcing Interactive Mode! This is only meant for self-testing.' >&2
else
return
fi
;;
esac
function __bashrc_path_dir_bashrc_print () {
# print the directory path for this bash file
# Do not assume this is run from path $HOME. This allows sourcing companion
# .bash_profile and .bashrc from different paths.
[[ ${#} -eq 0 ]] || return 1
declare path=${BASH_SOURCE:-}/..
if which dirname &>/dev/null; then
path=$(command -p dirname -- "${BASH_SOURCE:-}")
fi
if ! [[ -d "${path}" ]]; then
path=~ # in case something is wrong, fallback to ~
fi
echo -n "${path}"
}
#__bashrc_path_dir_bashrc=
__bashrc_path_dir_bashrc=$(__bashrc_path_dir_bashrc_print)
if ! [[ -d "${__bashrc_path_dir_bashrc}" ]]; then
__bashrc_path_dir_bashrc=~
fi
# $__bash_profile_import_start is defined in companion .bash_profile
# XXX: OpenSUSE Linux will import .bashrc first and then .bash_profile
# Forcibly import .bash_profile first and then .bashrc
if ! [[ "${__bash_profile_import_start+x}" ]]; then
echo "WARNING: .bashrc imported before .bash_profile; source .bash_profile anyway" >&2
source "${__bashrc_path_dir_bashrc}/.bash_profile"
return
fi
# function readlink_portable *should* be defined in companion .bash_profile. But
# in case was not defined, create a stub function
if ! type -t readlink_portable &>/dev/null; then
echo "WARNING: readlink_portable is not defined; was .bash_profile imported?" >&2
function readlink_portable () {
echo -n "${@}"
}
fi
# protect against initialization files that may source in a loop
__bashrc_initialized_flag="$(readlink_portable "${BASH_SOURCE:-}" 2>/dev/null) (${SHLVL})"
if [[ "${__bashrc_initialized+x}" ]] \
&& [[ "${__bashrc_initialized:-}" = "${__bashrc_initialized_flag}" ]]; then
echo "Skip duplicate initialization of '${__bashrc_initialized}'" >&2
return
fi
export __bashrc_initialized=${__bashrc_initialized_flag}
# stash current SHOPTS and ALIASES
bash_at_init_BASHOPTS=${BASHOPTS-}
bash_at_init_BASH_ALIASES=${BASH_ALIASES[@]-}
# note Bash Version
declare -i BASH_VERSION_MAJOR=${BASH_VERSINFO[0]}
declare -i BASH_VERSION_MINOR=${BASH_VERSINFO[1]}
export BASH_VERSION_MAJOR \
BASH_VERSION_MINOR
# prints an error message when the shift count exceeds the number of positional
# parameters
shopt -s shift_verbose
# ----------------------------------------
# very important helper `bash_installed`
# ----------------------------------------
# TODO: use `command -p which` to check paths. How to confine paths to only
# check those in `command -p`?
# TODO: follow-on to prior, add new function for using `which` with current
# `PATH` setting
# XXX: this function overwrites that in .bash_profile
__bash_installed_which_warning=false # global
__bash_installed_which= # global
function bash_installed () {
# are all passed args found in the $PATH?
if [[ "${__bash_installed_which}" != '' ]]; then
# assuming `which` was found then this will be the path taken for all
# remaining calls to this function after the first call
# XXX: bash 3 wants this one particular array expansion to have fallback
# value
# TODO: why are other resolutions of `${@}` not changed to `${@-}`?
if ! command -p "${__bash_installed_which}" "${@:-}" &>/dev/null; then
return 1
fi
return 0
fi
# if `which` was never found, then print this warning
if ${__bash_installed_which_warning}; then
return 1
fi
# check that 'which' exists, cache the `which` exists (via bash command
# caching) before any more paths are added to $PATH.
# on Git4Windows (specialized MinGW environment), which functions but is not
# in the $PATH so check for notepad.exe.
# this presumes that default $PATH will be the safest and most standard
if [[ "${__bash_installed_which}" = '' ]] \
&& ! (command -p which 'which' || command -p which 'notepad.exe') &> /dev/null; then
# print warning once
__bash_installed_which_warning=true
echo "WARNING: 'which' was not found in current \$PATH. This will limit features from this '${0}'" >&2
echo " Current Path:" >&2
echo " ${PATH}" >&2
return 1
elif [[ "${__bash_installed_which}" = '' ]]; then
# should only be set once
__bash_installed_which=$(command -p which which 2>/dev/null)
# on Git4Windows (specialized MinGW environment), which functions yet is not
# in the $PATH. So force this to work.
if [[ "${__bash_installed_which}" = '' ]] && command -p which 'notepad.exe' &>/dev/null; then
__bash_installed_which=which
fi
fi
if [[ ${#} -eq 0 ]]; then
return 0
elif ! [[ "${__bash_installed_which}" = '' ]]; then
# this is the first call of this function `bash_installed` but it was
# called with passed parameters so go ahead and check those parameters
bash_installed "${@-}"
fi
}
# run `bash_installed` once so $__bash_installed_which_warning and
# $__bash_installed_which is properly set
bash_installed
# other sanity warnings (most likely the PATH is screwed up)
# TODO: replace presumed use of these programs with bash built-in alternatives
for __bashrc_prog_sanity_check in dirname cat tr cut; do
if ! bash_installed "${__bashrc_prog_sanity_check}"; then
echo "WARNING: typical Unix program '${__bashrc_prog_sanity_check}' not found in PATH; this shell will behave poorly" >&2
fi
done
unset __bashrc_prog_sanity_check
# set some "cached" lookups for often needed programs
__bash_installed_tr=false # global
if bash_installed tr; then
__bash_installed_tr=true
fi
__bash_installed_id=false # global
if bash_installed id; then
__bash_installed_id=true
fi
# ---------------------------------------
# functions for sourcing other bash files
# ---------------------------------------
# create $__bash_processed_files_array if it does not exist
if ! [[ "${__bash_processed_files_array+x}" ]] ; then
# XXX: backward-compatible array declaration
__bash_processed_files_array[0]='' # global array
unset __bash_processed_files_array[0]
fi
# .bash_profile should have created $__bash_sourced_files_array only create if
# not already created
if ! [[ "${__bash_sourced_files_array+x}" ]]; then
# XXX: backward-compatible array declaration
__bash_sourced_files_array[0]='' # global array
unset __bash_sourced_files_array[0]
echo "WARNING: __bash_sourced_files_array was not already created" >&2
fi
# note this .bashrc file!
__bash_sourced_files_array[${#__bash_sourced_files_array[@]}]=$(readlink_portable "${BASH_SOURCE:-}")
function bash_source_file () {
# source a file with some preliminary checks, print a debug message
[[ ${#} -eq 1 ]] || return 1
# shellcheck disable=SC2155
declare -r sourcef=$(readlink_portable "${1}")
if [[ ! -f "${sourcef}" ]]; then
# missing file, no error
return
fi
if [[ ! -r "${sourcef}" ]]; then
# file exists but is not readable, error
return 1
fi
echo "${PS4-}source '${sourcef}' from '${BASH_SOURCE:-}'" >&2
# check if $sourcef has already been sourced, but only warn user if it has been
declare -i __i=0
declare -ir __len=${#__bash_sourced_files_array[@]}
while [[ ${__i} -lt ${__len} ]]; do
if [[ "${sourcef}" = "${__bash_sourced_files_array[${__i}]}" ]]; then
echo "WARNING: have previously sourced '${sourcef}'" >&2
break
fi
__i=$((${__i} + 1))
done
__bash_sourced_files_array[${#__bash_sourced_files_array[@]}]=${sourcef}
# shellcheck disable=SC1090
source "${sourcef}"
}
function bashrc_source_file () {
# backward-compatible wrapper
bash_source_file "${@}"
}
# .bashrc.local for host-specific customizations to run before the remainder of
# this .bashrc
bash_source_file "${__bashrc_path_dir_bashrc}/.bashrc.local.pre"
# shellcheck disable=SC2034
__bashrc_PATH_original=${PATH}
# ==============
# PATH additions
# ==============
# TODO: allow prepending path to front of $PATH
# bash_path_prepend ()
# change bash_path_add to __bash_path_add and allow $2 for position to
# insert
# add PATHs sooner so calls to `bash_installed` will search *all* paths the
# user has specified
function bash_path_pend () {
# append or prepend path $1 to $PATH but only if it is:
# - valid executable directory
# - not already in $PATH
# $2 if true will append, if false will prepend. Optional.
[[ ${#} -eq 1 || ${#} -eq 2 ]] || return 1
declare -r path=${1}
declare -r append=${2:-true}
# must be valid executable directory or symlink
if [[ ! -d "${path}" && ! -L "${path}" ]] || [[ ! -x "${path}" ]]; then
return 1
fi
# a relative directory should be resolved to full path using `realpath`.
# do not resolve symlinks in that path (`readlink` always resolves
# symlinks).
declare pathr=
if bash_installed realpath; then
if ! pathr=$(realpath --no-symlinks "${path}" 2>/dev/null); then
pathr=${path}
fi
else
pathr=${path}
fi
# test if any attempts at primitive matching find a match (substring $path
# within $PATH?)
# uses primitive substring matching and avoid =~ operator as the path $1
# could have regex
# significant characters
# test front
# test back
# test middle
if ! { [[ "${PATH}" = "${PATH##${pathr}:}" ]] \
&& [[ "${PATH}" = "${PATH%%:${pathr}}" ]] \
&& [[ "${PATH}" = "${PATH/:${pathr}:/}" ]] ;
}
then
return 1
fi
if ${append}; then
echo "${PS4-}bash_path_append '${pathr}'" >&2
export PATH=${PATH}:${pathr}
else
echo "${PS4-}bash_path_prepend '${pathr}'" >&2
export PATH=${pathr}:${PATH}
fi
}
# wrapper for bash_path_pend to append
function bash_path_append () {
bash_path_pend "${1}" true
}
# wrapper for bash_path_pend to prepend
function bash_path_prepend () {
bash_path_pend "${1}" false
}
# backwards-compatible wrapper for bash_path_pend to append
function bash_path_add () {
bash_path_pend "${1}" true
}
# backwards-compatible public-facing wrapper for bash_path_add, allows multiple
# arguments
function bash_paths_add () {
[[ ${#} -gt 0 ]] || return 1
declare path_=
declare -i ret=0
for path_ in "${@}"; do
if ! bash_path_add "${path_}"; then
ret=1
fi
done
return ${ret}
}
function __bashrc_path_add_from_file () {
# attempt to add paths found in the file $1, assuming a path per-line
[[ ${#} -eq 1 ]] || return 1
declare path=
declare -r paths_file=${1}
if [[ -r "${paths_file}" ]]; then
__bash_processed_files_array[${#__bash_processed_files_array[@]}]=$(readlink_portable "${paths_file}")
while read -r path; do
bash_path_add "${path}"
done < "${paths_file}"
else
return 1
fi
}
# print the path nicely for the user, highlight errors
function bash_path_print () {
# print $PATH, one path per line, colorize according to any issues
# test with
# (set -eu; mkdir /tmp/a; chmod 444 /tmp/a; PATH="$PATH:foo:bar:foo:/usr/bin:/usr/sbin:/usr/sbin:/usr/sbin:/usr/bin:/NO/EXIST:/usr/bin/sh:/tmp/a:/tmp/a" export PATH; bash_path_print)
# $1 may be --verbose or -v
#
# the user can pipe to `column` to print a nice table
# bash_path_print -v | column -t -s $'\t'
#
declare verbose=false
if [[ "${1-}" = '-v' ]] || [[ "${1-}" = '--verbose' ]]; then
verbose=true
elif [[ "${1-}" != '' ]]; then
# passed unknown argument
echo "ERROR bash_path_print received unknown argument '${1-}'" >&2
return 1
fi
declare path=
# XXX: runtime O(n^2)
# TODO: if bash 4 then use associative array which I presume is O(1) lookup
declare -a paths=( '' )
declare color_end='\e[0m'
if ! ${__bashrc_color}; then
# color is turned off so do not print color escape codes
color_end=''
fi
while read -r path; do
# does it exist and is it a directory?
declare exists=false
declare is_dir=false
declare is_exec=false
if [[ -e "${path}" ]]; then
exists=true
if [[ -d "${path}" ]]; then
is_dir=true
if [[ -x "${path}" ]]; then
is_exec=true
fi
fi
fi
# check if current $path is the same `realpath` as any prior $path
declare duplicate=false
declare p2=
for p2 in "${paths[@]}"; do
if [[ "${p2}" = '' ]]; then
continue
fi
declare rp1=$(realpath "${path}" 2>/dev/null)
declare rp2=$(realpath "${p2}" 2>/dev/null)
if [[ "${rp1}" = "${rp2}" ]]; then
duplicate=true
break
fi
done
paths[${#paths[@]}]=${path}
# print $path with colors depending upon what was found out about it
declare color=''
if ! ${exists}; then
# red
color='\e[31m'
fi
if ${exists} && ! ${is_dir}; then
# light yellow
color='\e[93m'
fi
if ${exists} && ${is_dir} && ! ${is_exec}; then
# magenta
color='\e[35m'
fi
declare color_duplicate=''
if ${duplicate}; then
# dim
color_duplicate='\e[2m'
fi
if ! ${__bashrc_color}; then
# color is turned off so do not print color escape codes
color=''
color_duplicate=''
fi
echo -ne " ${color}${color_duplicate}${path}${color_end}"
if ${verbose}; then
echo -en "\texists? ${exists},\tis dir? ${is_dir},\tis executable? ${is_exec},\tduplicate? ${duplicate}"
fi
echo
done < <(echo "${PATH//:/
}")
}
# ============================
# other misc. helper functions
# ============================
# ordinal and character copied from https://unix.stackexchange.com/a/92448/21203
function ordinal () {
# pass a single-character string, prints the numeric ordinal value
if [[ ${#} -ne 1 ]]; then
echo "ERROR function ordinal requires passing one argument" >&2
return 1
fi
(LC_CTYPE=C command -p printf '%d' "'${1:0:1}")
}
function character () {
# pass a number, prints the character
if [[ ${#} -ne 1 ]]; then
echo "ERROR function character requires passing one argument" >&2
return 1
fi
[ "${1}" -lt 256 ] || return 1
command -p printf "\\$(printf '%03o' "${1}")"
}
function bash_print_OS () {
# Print a useful string about this OS
# If nothing can be determined the return 1.
#
# See also
# http://whatsmyos.com/
# https://stackoverflow.com/a/27776822/471376
#
# TODO: this function is a bit of a mess and needs some consistency about
# what it is aiming to do.
# TODO: this function could use bash variable $OSTYPE
# TODO: not tested adequately on non-Linux
if [[ ${#} -ne 0 ]]; then
echo "ERROR function bash_print_OS takes no arguments" >&2
return 1
fi
declare uname_=$(uname -s) 2>/dev/null || true
if [[ -e /proc/version ]] || [[ "${OSTYPE+x}" = 'linux-gnu' ]]; then
# most likely a Linux
if [[ -r /etc/os-release ]]; then
# five examples of /etc/os-release (can you spot the bug?)
#
# PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
# NAME="Raspbian GNU/Linux"
# VERSION_ID="9"
# VERSION="9 (stretch)"
# ID=raspbian
# ID_LIKE=debian
# HOME_URL="http://www.raspbian.org/"
# SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
# BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
#
# NAME="Alpine Linux"
# ID=alpine
# VERSION_ID=3.10.0
# PRETTY_NAME="Alpine Linux v3.10"
# HOME_URL="https://alpinelinux.org/"
# BUG_REPORT_URL="https://bugs.alpinelinux.org/"
#
# NAME="Ubuntu"
# VERSION="18.04.3 LTS (Bionic Beaver)"
# ID=ubuntu
# ID_LIKE=debian
# PRETTY_NAME="Ubuntu 18.04.3 LTS"
# VERSION_ID="18.04"
# HOME_URL="https://www.ubuntu.com/"
# SUPPORT_URL="https://help.ubuntu.com/"
# BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
# PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
# VERSION_CODENAME=bionic
# UBUNTU_CODENAME=bionic
#
# NAME="CentOS Linux"
# VERSION="7 (Core)"
# ID="centos"
# ID_LIKE="rhel fedora"
# VERSION_ID="7"
# PRETTY_NAME="CentOS Linux 7 (Core)"
# ANSI_COLOR="0;31"
# CPE_NAME="cpe:/o:centos:centos:7"
# HOME_URL="https://www.centos.org/"
# BUG_REPORT_URL="https://bugs.centos.org/"
# CENTOS_MANTISBT_PROJECT="CentOS-7"
# CENTOS_MANTISBT_PROJECT_VERSION="7"
# REDHAT_SUPPORT_PRODUCT="centos"
# REDHAT_SUPPORT_PRODUCT_VERSION="7"
#
# NAME=Fedora Remix for WSL
# VERSION="29"
# ID=fedoraremixforwsl
# ID_LIKE=fedora
# VERSION_ID=29
# PLATFORM_ID="platform:f29"
# PRETTY_NAME="Fedora Remix for WSL"
# ANSI_COLOR="0;34"
# CPE_NAME="cpe:/o:fedoraproject:fedora:29"
# HOME_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL"
# SUPPORT_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL"
# BUG_REPORT_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL/issues"
# PRIVACY_POLICY_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL/blob/master/PRIVACY.md"
#
(
set +u
set -e
# XXX: potential bug in the Fedora WSL file
# shellcheck disable=SC2046
source /etc/os-release 2>/dev/null || exit 1
echo -n "${PRETTY_NAME-${NAME-} ${VERSION_ID-}}"
) && return
elif [[ -r /etc/centos-release ]]; then
# example file `/etc/centos-release` from older CentOS
#
# CentOS release 6.7 (Final)
#
declare centos=$(cat /etc/centos-release 2>/dev/null)
# delete everything after the first newline
echo -n "${centos%%
*}"
return
elif [[ -r /etc/redhat-release ]]; then
echo -n 'Redhat Linux'
return
elif [[ "${uname_}" == CYGWIN* ]]; then
echo -n "${uname_}"
return
elif [[ "${uname_}" == MINGW* ]]; then
echo -n "MinGW ${uname_}"
return
elif [[ "${uname_}" == MSYS* ]]; then
echo -n "${uname_}"
return
elif [[ "${uname_}" == Darwin* ]]; then
echo -n "Mac ${uname_}"
return
fi
fi
# most likely a Unix
declare sysctl_output=
# BSD specific system call (AFAIK)
if sysctl_output=$(sysctl -n kern.osrelease kern.ostype 2>/dev/null); then
# try `uname` again because `uname -s -r` only shows `NetBSD 9.3`
# whereas Linux kernels include the arch in the `-r` output
uname_=$(uname -s -r -p 2>/dev/null)
if [[ "${uname_}" != '' ]]; then
echo -n "${uname_%%
*}"
return
fi
echo -n "${sysctl_output}"
return
fi
# program unique to Solaris (AFAIK)
if bash_installed showrev; then
echo -n 'Solaris Unix'
return
fi
if [[ "${uname_}" != '' ]]; then
echo -n "${uname_}"
return
fi
return 1
}
__bashrc_OperatingSystem=$(bash_print_OS) || true
function __bashrc_replace_str () {
# Portable string replacement not reliant on `sed`, `awk`
# Given string $1, replace substring $2 with string $3 then echo the result.
#
# This function is the most portable method for doing such. Programs like
# `sed` and `awk` vary too much or may not be available. Often, a bash
# substring replacement (e.g. `${foo//abc/123}`) suffices but bash 3.2
# does not recognize '\t' as tab character.
#
# tested variations on implemention of this with function using command:
#
# $ bash -i -c 'trap times EXIT; table="A BB CCC DDDD"; source .func;
# for i in {1..10000}; do
# __bashrc_replace_str "${table}" " " " " >/dev/null
# done;'
#
[[ ${#} -eq 3 ]] || return 1
# try bash substring replacement because it's faster, make sure it supports
# replacing in-line tab character
declare testvar=' '
if echo -n "${testvar/ / }" &>/dev/null; then
# about 10% faster if the substitution is done for a variable and then
# echoed instead as versus directly echoed (i.e. two statements is
# faster than one statement)
testvar=${1//${2}/${3}}
echo -n "${testvar}"
return
fi
# bash substring replacement failed so use slower fallback
# Fallback method is about x6 slower than bash substring replacement.
declare out=''
declare -ir l1=${#1} # strlen of $1
declare -ir l2=${#2} # strlen of $2
declare -i at=0 # index current
declare -i atb=0 # index of beginning of next replacement
while [[ ${at} -lt ${l1} ]]; do
if [[ "${1:${at}:${l2}}" == "${2}" ]]; then
out+=${1:${atb}:${at}-${atb}}${3}
at=$((at+l2))
atb=${at}
else
at=$((at+1))
fi
done
if [[ ${at} -ne ${atb} ]]; then
out+=${1:${atb}:${at}-${atb}}
fi
echo -n "${out}"
}
function __bashrc_tab_str () {
# prepend tabs after each newline
# optional $2 is tab count
# optional $3 is replacement string
[[ ${#} -gt 0 ]] || return 1
[[ ${#} -le 3 ]] || return 1
declare -ri tab_count=${2-1}
declare -r repl=${3-
}
__bashrc_replace_str "${1}" "${repl}" "
$(for ((i = 0; i < tab_count; i++)); do echo -n ' '; done)"
}
function line_count () {
# count '\n' in stdin as parsed by `read` builtin
# input '' yields "0"
# input 'a' yields "1"
# input 'a\n' yields "2"
# input 'a\nb' yields "2"
# input 'a\nb\n' yields "2"
# input 'a\nb\nc' yields "3"
#
# portable line count, not reliant on `wc -l`
#
if [[ ${#} -ne 0 ]]; then
echo "ERROR function line_count takes no arguments; data is read from stdin" >&2
return 1
fi
declare line=
declare -i count=0
while read -rs line; do
count=$((count + 1))
done
if [[ "${line}" != '' ]]; then
count=$((count + 1))
fi
command echo -n "${count}"
}
function am_i_root {
# is the current user root?
if [[ ${#} -ne 0 ]]; then
echo "ERROR function am_i_root takes no arguments" >&2
return 2
fi
if ! ${__bash_installed_id}; then
return 2
fi
if [[ "$(command -p id -u 2>/dev/null)" = "0" ]]; then
return 0
fi
return 1
}
function env_sorted () {
# Print environment sorted
# Accounts for newlines within environment values (common in $LS_COLORS)
if [[ ${#} -ne 0 ]]; then
echo "ERROR function env_sorted takes no arguments" >&2
return 1
fi
if ! bash_installed env sort tr; then
return 1
fi
# The programs env and sort may not supported the passed options. Shell
# option `pipefail` will cause immediate exit if any program fail in the
# pipeline fails. This function will return that failure code.
(
set -e
set -o pipefail
env --null 2>/dev/null \
| sort --zero-terminated 2>/dev/null \
| tr '\000' '\n' 2>/dev/null
)
}
# Record original environment variables for later diff
# shellcheck disable=SC2034
__bashrc_env_0_original=$(env_sorted)
function var_is_array () {
# each arg is the name of a variable, return 0 if all args are type array,
# else return 1
if [[ ${#} -eq 0 ]]; then
echo "ERROR function var_is_array must be passed a variable name" >&2
return 1
fi
declare arg=
for arg in "${@}"; do
declare out=$(declare -p "${arg}" 2>/dev/null)
if ! expr match "${out}" '^declare -.*[Aa].* ' &>/dev/null; then
return 1
fi
done
return 0
}
function var_is_int () {
# each arg is the name of a variable, return 0 if all args are type integer,
# else return 1
if [[ ${#} -eq 0 ]]; then
echo "ERROR function var_is_int must be passed a variable name" >&2
return 1
fi
declare arg=
for arg in "${@}"; do
declare out=$(declare -p "${arg}" 2>/dev/null)
if ! expr match "${out}" '^declare -.*i.* ' &>/dev/null; then
return 1
fi
done
return 0
}
function bash_print_var () {
# print the value of a variable
if [[ ${#} -ne 1 ]]; then
echo "ERROR function bash_print_var must be passed one variable name" >&2
return 1
fi
declare -r var=${1}
if [[ ! "${!var+x}" ]]; then
echo "VARIABLE '${var}' NOT DEFINED" >&2
return
fi
if var_is_array "${var}"; then
declare -p "${var}"
#if [[ "${#var[@]}" -eq 0 ]]; then
# echo "${var}=()"
# continue
#fi
#declare index=
#for index in "${!var[@]}"; do
# echo "${var[${index}]}='${!var[${index}]}'"
#done
elif var_is_int "${var}"; then
declare -p "${var}"
#echo "${var}=${!var}"
else
declare -p "${var}"
#echo "${var}='${!var}'"
fi
}
function bash_print_special_shell_vars () {
# print all the bash special and dynamic variables
# taken from:
# https://wiki.bash-hackers.org/syntax/shellvars
# (https://archive.ph/u0EGp)
#
declare -ar vars=(
'*'
'@'
'?'
'#'
'-'
'!'
'0'
'_'
BASH
BASHOPTS
BASHPID
BASH_ALIASES
BASH_ARGC
BASH_ARGV
BASH_ARGV0
BASH_CMDS
BASH_COMMAND
BASH_COMPAT
BASH_ENV
BASH_EXECUTION_STRING
BASH_LINENO
BASH_REMATCH
BASH_SOURCE
BASH_SUBSHELL
BASH_VERSINFO
BASH_VERSION
BASH_XTRACEFD
CDPATH
CHILD_MAX
COLUMNS
COMP_CWORD
COMP_KEY
COMP_LINE
COMP_POINT
COMPREPLY
COMP_TYPE
COMP_WORDBREAKS
COMP_WORDS
COPROC
DIRSTACK
EMACS
ENV
EPOCHREALTIME
EPOCHSECONDS
EUID
FCEDIT
FIGNORE
FUNCNAME
FUNCNEST
GLOBIGNORE
GROUPS
HISTCMD
HISTCONTROL
HISTFILE
HISTFILESIZE
HISTIGNORE