-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bash.config
executable file
·1053 lines (1026 loc) · 36.3 KB
/
bash.config
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
# -*- mode: bash; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: t-*-
# vi: set ft=bash noet ci pi sts=0 sw=2 ts=2:
# st:
#
#
# # /usr/bin/env bash
#
# bash.sh:
# Standard Template for bash/zsh developing.
# Version: v20241112
# License: MIT
# Site: https://github.com/hedzr/bash.sh
#
# Usages:
# $ ./bash.sh cool
# $ DEBUG=1 ./bash.sh
#
# $ ./bash.sh debug-info
#
# $ ./bash.sh 'is_root && echo Y'
# $ sudo ./bash.sh 'is_root && echo Y'
# $ sudo DEBUG=1 ./bash.sh 'is_root && echo y'
#
# $ HAS_END=: ./bash.sh
# $ HAS_END=false ./bash.sh
#
# Use installer (Deprecated):
# $ curl -sSL https://hedzr.com/bash.sh/installer | sudo bash -s
#### write your functions here, and invoke them by: `./bash.sh <your-func-name>`
# FN_PREFIX=boot_
_my_main_do_sth() {
local cmd=${1:-help} && { [ $# -ge 1 ] && shift; } || :
# local FN_PREFIX=boot_
# for linux only:
# local cmd=${1:-sleeping} && && shift || :
local DBG_SAVE="$DEBUG"
dbg "[importing files]: loading ..."
_bash_sh_load_import_files
dbg "[importing files]: shell.d/ops.d files"
# _bash_sh_load_files '*'
_bash_sh_load_env_files
dbg "[importing files]: .env done"
# in_provisioning ||
[ "$cmd" = "first-install" ] || DEBUG="$DBG_SAVE" # && echo "DEBUG: $DEBUG"
# echo "4. DEBUG: $DEBUG, cmd: $cmd"
# in_debug && LC_ALL=C type $cmd || echo "$cmd not exists"
dbg ": invoking cmd: $cmd"
local xcmd="${cmd//-/_}"
dbg ": trying cmd: $xcmd ..."
if fn_exists "$xcmd"; then
eval $xcmd "$@" #&& dbg ":DONE:$cmd"
elif fn_exists "boot_$xcmd"; then
eval boot_$xcmd "$@" #&& dbg ":DONE:$cmd"
elif fn_aliased_exists "$xcmd"; then
eval $xcmd "$@" #&& dbg ":DONE:$cmd"
else
xcmd="${cmd//_/-}"
dbg ": trying cmd: $xcmd ..."
if fn_exists "$xcmd"; then
eval $xcmd "$@" #&& dbg ":DONE:$cmd"
elif fn_exists "boot-$xcmd"; then
eval boot-$xcmd "$@" #&& dbg ":DONE:$cmd"
elif fn_aliased_exists "$xcmd"; then
eval $xcmd "$@" #&& dbg ":DONE:$cmd"
else
local f="$CD/ops.d/run/$cmd.sh"
# dbg " ..finding $f"
if [ -f "$f" ]; then
dbg " ..sourcing $(safety $f).." && source "$f" && dbg " ..OK"
if fn_exists "${cmd}_entry"; then
# dbg " ..eval '${cmd}_entry' $@"
${cmd}_entry "$@"
else
eval $cmd "$@"
fi
else
err "command '$cmd' has not been defined. (CD=$(safety $CD))"
return
fi
fi
fi
# unset xcmd
if in_provisioning; then
if [ -f "$CD/after.sh" ]; then
headline "Sourcing and Running after.sh ..."
source "$CD/after.sh"
if fn_exists "after_provision"; then
eval "after_provision" "$@"
else
:
fi
fi
if [ -f "$CD/user-customizations.sh" ]; then
headline "Sourcing and Running user-customizations.sh ..."
source "$CD/user-customizations.sh"
if fn_exists "user_custom"; then
eval "user_custom" "$@"
else
:
fi
fi
dbg ":DONE:END:$(fn_name_dyn):$?"
else
HAS_END=0
fi
}
_bash_sh_try_source_in() {
local f
for f in "$@"; do
[ -f "$f" ] && shift && dbg " ..sourcing $(safety $f)" && DEBUG=0 VERBOSE=0 source "$f"
done
}
_bash_sh_try_source_child_files() {
local dir="$1"
# processed=0
if [ -d $dir ]; then
if test -n "$(find $dir -maxdepth 1 -name '*.sh' -print -quit)"; then
for f in $dir/*.sh; do dbg " ..sourcing $(safety $f)" && source $f && processed=1; done
else
tip " nothing for testing $(safety $dir)/*.sh, PWD: $(pwd)"
fi
else
:
fi
}
_bash_sh_load_import_files() {
local dir processed=0
local osid="$(osid)" pmid="$(pmid)"
for dir in $CD; do
if [ -d $dir/ops.d ]; then
_bash_sh_try_source_child_files "$dir/ops.d" # && tip "processed = $processed"
_bash_sh_try_source_child_files "$dir/ops.d/$osid"
_bash_sh_try_source_child_files "$dir/ops.d/$pmid"
else
dbg "[DBUG] $(safety $dir)/ops.d/ folder NOT FOUND, no more script files loaded."
fi
done
if [[ $processed -eq 0 ]]; then
# in_debug && is_darwin && ps -a || ps -auxf
dbg
dbg "CD=$(safety $CD), SCRIPT=$(safety $SCRIPT)"
dbg "[NOTE] ops.d/ folder NOT FOUND, no more script files loaded."
else
:
fi
}
_bash_sh_load_files() {
local f ff dir processed=0
dbg " > load_files $(safety $@) <"
for dir in "$CD"; do
if [ -d "$dir/ops.d" ]; then
for f in "$@"; do
local s="$dir/ops.d/$f.sh"
dbg " ..testing for $(safety $s) ..."
if test -n "$(find $dir/ops.d -maxdepth 1 -name $f'.sh' -print -quit)"; then
for ff in $dir/ops.d/$f.sh; do dbg " ..sourcing $(safety $ff)" && source $ff && processed=1; done
else
:
fi
# if [ -f $s ]; then
# dbg " ..sourcing $(safety $s)" && source $s && processed=1
# fi
done
else
:
fi
done
if [[ $processed -eq 0 ]]; then
# in_debug && is_darwin && ps -a || ps -auxf
dbg
dbg "CD=$(safety $CD), SCRIPT=$(safety $SCRIPT)"
dbg "[NOTE] ops.d/ folder NOT FOUND, no more script files loaded."
else
:
fi
}
_bash_sh_load_env_files() {
local rel env=
for rel in '.' '..'; do
env="$CD/$rel/.env"
[ -f $env ] && { dbg " ..sourcing $(safety $env)" && source $env; } || :
done
for env in "$CD/ops.d/.env" "$CD/.env.local" "$CD/ops.d/.env.local" "$HOME/.config/ops.sh/env"; do
[ -f $env ] && { dbg " ..sourcing $(safety $env)" && source $env; } || :
done
:
}
########################################################
#### HZ Tail BEGIN #### v20241112 ####
in_debug() { (($DEBUG)); }
in_provisioning() { (($PROVISIONING)); } ## return exit status as true if $PROVISIONING is not equal to 0
is_root() { [ "$(id -u)" = "0" ]; }
is_bash() { is_bash_t1 || is_bash_t2; }
is_bash_t1() { [ -n "$BASH_VERSION" ]; }
is_bash_t2() { [ ! -n "$BASH" ]; }
is_bash_strict() { if is_bash; then if is_zsh_strict; then false; else true; fi; else false; fi; }
is_zsh() { [[ -n "$ZSH_NAME" || "$SHELL" = */zsh ]]; }
is_zsh_strict() { [[ -n "$ZSH_NAME" && "$SHELL" = */zsh ]]; }
is_zsh_t1() { [[ "$SHELL" = */zsh ]]; }
is_zsh_t2() { [ -n "$ZSH_NAME" ]; }
is_fish() { [ -n "$FISH_VERSION" ]; }
is_darwin() { [[ $OSTYPE == darwin* ]]; }
is_darwin_sillicon() { is_darwin && [[ $(uname_mach) == arm64 ]]; }
is_linux() { [[ $OSTYPE == linux* ]]; }
is_win() { in_wsl; }
in_wsl() { [[ "$(uname -r)" == *windows_standard* ]]; }
in_sourcing() {
# https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced
if is_zsh; then
[[ "$ZSH_EVAL_CONTEXT" == *:file:* ]]
else
[[ $(basename -- "$0") != $(basename -- "${BASH_SOURCE[0]}") ]]
fi
}
in_vscode() { [[ "$TERM_PROGRAM" == "vscode" ]]; } # or VSCODE_INJECTION=1
in_jetbrains() { [[ "$TERMINAL_EMULATOR" == *JetBrains* ]]; }
in_vim() { [[ "$VIM" != "" ]] && [[ "$VIMRUNTIME" != "" ]]; }
in_neovim() { [[ "$NVIM" != "" ]] || [[ "$NVIM_LOG_FILE" != "" ]] || [[ "$NVIM_LISTEN_ADDRESS" != "" ]]; }
is_interactive_shell() { [[ $- == *i* ]]; }
is_not_interactive_shell() { [[ $- != *i* ]]; }
is_ps1() { [ -z "$PS1" ]; }
is_not_ps1() { [ ! -z "$PS1" ]; }
# The [ -t 1 ] check only works when the function is not called from
# a subshell (like in `$(...)` or `(...)`, so this hack redefines the
# function at the top level to always return false when stdout is not
# a tty.
if [ -t 1 ]; then
alias is_stdin=true
alias is_not_stdin=false
alias is_ttya=true
else
alias is_stdin=false
alias is_not_stdin=true
alias is_ttya=false
fi
cmd_exists() { command -v $1 >/dev/null; } # it detects any builtin or external commands, aliases, and any functions
fn_exists() { LC_ALL=C type $1 2>/dev/null | grep -qE '(shell function)|(a function)'; }
fn_builtin_exists() { LC_ALL=C type $1 2>/dev/null | grep -q 'shell builtin'; }
fn_aliased_exists() { LC_ALL=C type $1 2>/dev/null | grep -qE '(alias for)|(aliased to)'; }
fn_name() {
is_zsh && local fn_="${funcstack[2]}"
if [ "$fn_" = "" ]; then
is_bash && echo "${FUNCNAME[1]}"
else
echo "$fn_"
fi
# is_zsh && echo "${funcstack[2]}" || {
# is_bash && echo "${FUNCNAME[1]}"
# }
}
currentShell=
fn_name_dyn() {
if is_darwin; then
is_zsh && local fn_="${funcstack[2]}"
if [ "$fn_" = "" ]; then
is_bash && echo "${FUNCNAME[1]}"
else
echo "$fn_"
fi
return
fi
# local currentShell=$(ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-')
currentShell=${currentShell:-$(find_shell_by_pidtree)}
if [[ $currentShell == *'bash' ]]; then
echo ${FUNCNAME[1]}
elif [[ $currentShell == *'zsh' ]]; then
echo ${funcstack[2]}
else
echo "unknown func name ($currentShell)"
fi
}
ps_get_procname() { ps -hp ${1:-$$} | awk '{print $4}'; }
ps_get_fullprocname() { ps -fhp ${1:-$$} | awk '{ for (i=5;i<=NF-1;i++) { printf "%s ", $i }; printf "\n" }'; }
ps_get_procpath() { ps -hp ${1:-$$} | awk '{ if(NF>6) print $6; else print $5 }'; }
user_shell() { grep -E "^${1:-$USER}:" /etc/passwd | awk -F: '{print $7}'; }
top_level_parent_pid() { # cannot work under darwin
# Look up the parent of the given PID.
local pid=${1:-$$}
local ppid="$(awk '/^PPid:/ { print $2 }' </proc/"$pid"/status)"
# /sbin/init always has a PID of 1, so if you reach that, the current PID is
# the top-level parent. Otherwise, keep looking.
if [[ ${ppid} -eq 1 ]]; then
echo "${pid}"
else
top_level_parent_pid "${ppid}"
fi
}
find_shell_by_pidtree() { # cannot work under darwin
local pid=${1:-$$}
local ppid="$(awk '/^PPid:/ { print $2 }' </proc/"$pid"/status)"
local ppath="$(ps_get_fullprocname ${pid})"
local pbin="${ppath%% *}" # get first part by space separated
[ -f /tmp/tmp_pids ] && $SUDO chown $USER: /tmp/tmp_pids
[[ "$pbin" =~ ^- ]] && { echo bad >>/tmp/tmp_pids && local isshell=0; } || {
grep -qE "${pbin}" /etc/shells
[[ $? -eq 0 ]] && local isshell=1 || local isshell=0
}
echo "$pid - $ppid - $ppath - $pbin - $isshell" >>/tmp/tmp_pids
if [[ $isshell -eq 1 || ${ppid} -eq 1 ]]; then
echo "${pbin}"
else
find_shell_by_pidtree "${ppid}"
fi
}
home_dir() { grep -E "^${1:-$USER}:" /etc/passwd | awk -F: '{print $6}'; }
homedir_s() {
local name=${1:-$USER}
local home=/home/$name
[ "$name" = "root" ] && home=/root
echo $home
}
if_zero_or_empty() {
if [ ! -z "$1" ]; then
[[ "$1" -eq 0 ]]
else
false
fi
}
if_non_zero_and_empty() {
if [ ! -z "$1" ]; then
[[ "$1" -ne 0 ]]
else
false
fi
}
#
#
#
if_nix_typ() {
case "$OSTYPE" in
*linux* | *hurd* | *msys* | *cygwin* | *sua* | *interix*) sys="gnu" ;;
*bsd* | *darwin*) sys="bsd" ;;
*sunos* | *solaris* | *indiana* | *illumos* | *smartos*) sys="sun" ;;
esac
echo "${sys}"
}
if_nix() { [[ "$(if_nix_typ)" == "$1" ]]; }
if_mac() { [[ $OSTYPE == darwin* ]]; }
if_ubuntu() {
if [[ $OSTYPE == linux* ]]; then
[ -f /etc/os-release ] && grep -qi 'ubuntu' /etc/os-release
fi
}
if_vagrant() { [ -d /vagrant ]; }
in_vagrant() { [ -d /vagrant ]; }
if_centos() {
if [[ $OSTYPE == linux* ]]; then
if [ -f /etc/centos-release ]; then
:
else
[ -f /etc/issue ] && grep -qEi '(centos|(Amazon Linux AMI))' /etc/issue
fi
fi
}
in_vm() {
if cmd_exists hostnamectl; then
# dbg "checking hostnamectl"
if hostnamectl | grep -iE 'chassis: ' | grep -q ' vm'; then
true
elif hostnamectl | grep -qE 'Virtualization: '; then
true
fi
else
# dbg "without hostnamectl"
false
fi
}
if_upstart() { [[ $(/sbin/init --version) =~ upstart ]]; }
if_systemd() { [[ $(systemctl) =~ -\.mount ]]; }
if_sysv() { [[ -f /etc/init.d/cron && ! -L /etc/init.d/cron ]]; }
#
#
#
pmid() { # apt, yum, dnf, brew, ...
is_apt && echo "apt" && return
is_dnf && echo "dnf" && return
is_yum && echo "yum" && return
is_pacman && echo "pacman" && return
is_zypp && echo "zypp" && return
is_homebrew && echo "brew" && return
# is_snap && echo "snap" && return
# is_chocolatey && echo "choco" && return
# is_scoop && echo "scoop" && return
# is_cargo && echo "cargo" && return
echo "???"
}
osid() { # fedora / ubuntu / debian / mageia / manjaro / arch ...
[[ -f /etc/os-release ]] && {
grep -Eo '^ID="?(.+)"?' /etc/os-release | sed -r -e 's/^ID="?([^"]+)"?/\1/'
} || {
is_darwin && echo "darwin" || {
is_win && echo "windows" || echo "unknown-os"
}
}
}
osidlike() { # redhat / debian / centos / fedora / redhat / mandriva fedora / arch ...
[[ -f /etc/os-release ]] && {
grep -Eo '^ID_LIKE="?(.+)"?' /etc/os-release | sed -r -e 's/^ID_LIKE="?([^"]+)"?/\1/'
} || {
is_darwin && echo "darwin" || {
is_win && echo "windows" || echo "unknown-os"
}
}
}
oscodename() { # focal / xenial / ... # = `lsb_release -cs`
[[ -f /etc/os-release ]] && {
grep -Eo '^VERSION_CODENAME="?(.+)"?' /etc/os-release | sed -r -e 's/^VERSION_CODENAME="?(.+)"?/\1/'
}
}
versionid() { # 33 / 20.04
[[ -f /etc/os-release ]] && {
grep -Eo '^VERSION_ID="?(.+)"?' /etc/os-release | sed -r -e 's/^VERSION_ID="?(.+)"?/\1/' | sed -r -e 's/"$//'
}
}
variantid() { # server, desktop
[[ -f /etc/os-release ]] && {
grep -Eo '^VARIANT_ID="?(.+)"?' /etc/os-release | sed -r -e 's/^VARIANT_ID="?(.+)"?/\1/' | sed -r -e 's/"$//'
}
}
#
is_fedora() { [[ "$(osid)" == fedora ]]; }
is_centos() { [[ "$(osid)" == centos ]]; }
is_redhat() { [[ "$(osid)" == redhat ]]; }
is_debian() { [[ "$(osid)" == debian ]]; }
is_ubuntu() { [[ "$(osid)" == ubuntu ]]; }
is_mageia() { [[ "$(osid)" == mageia ]]; }
is_manjaro() { [[ "$(osid)" == manjaro ]]; }
is_opensuse() { [[ "$(osid)" == opensuse* ]]; }
is_archlinux() { [[ "$(osid)" == arch* ]]; }
is_archlinux_arm() { [[ "$(osid)" == archarm* ]]; }
is_kalilinux() { [[ "$(osid)" == kali* ]]; }
# is_debian_series() { [[ "$(osid)" == debian || "$(osid)" == ubuntu ]]; }
# is_redhat_series() { [[ "$(osid)" == redhat || "$(osid)" == centos || "$(osid)" == fedora ]]; }
is_yum() { which yum 1>/dev/null 2>&1; }
is_dnf() { which dnf 1>/dev/null 2>&1; }
is_apt() { which apt-get 1>/dev/null 2>&1; }
is_pacman() { which pacman 1>/dev/null 2>&1; }
is_zypp() { which zypper 1>/dev/null 2>&1; }
is_zypper() { which zypper 1>/dev/null 2>&1; }
is_homebrew() { which brew 1>/dev/null 2>&1; }
# is_redhat_series() { is_yum || is_dnf; }
# is_debian_series() { is_apt; }
is_redhat_series() { [[ "$(osidlike)" == redhat ]]; }
is_debian_series() { [[ "$(osidlike)" == debian ]]; }
is_mandriva_series() { [[ "$(osidlike)" == mandriva* ]]; } # mandriva, mageia, ...
is_arch_series() { [[ "$(osidlike)" == arch ]]; }
is_fedora_series() { [[ "$(osidlike)" == *fedora* ]]; }
is_suse_series() { [[ "$(osidlike)" == suse* ]]; }
is_opensuse_series() { [[ "$(osidlike)" == *opensuse* ]]; }
#
#
#
lsb_release_cs() { which lsb_release 1>/dev/null 2>&1 && lsb_release -cs; } # focal, ... # = oscodename
uname_kernel() { uname -s; } # Linux
uname_cpu() { uname -p; } # processor: x86_64
uname_mach() { uname -m; } # machine: x86_64, ...
uname_rev() { uname -r; } # kernel-release: 5.8.15-301.fc33.x86_64
uname_ver() { uname -v; } # kernel-version:
lscpu_call() { lscpu $*; }
lshw_cpu() { $SUDO lshw -c cpu; }
i386_amd64() {
ar=""
case $(uname -m) in
i386 | i686) ar="386" ;;
x86_64) ar="amd64" ;;
armv7*) ar="arm" ;;
arm)
is_debian_series && {
dpkg --print-architecture | grep -q "arm64" && ar="arm64" || ar="arm"
} || { ar="arm64"; }
;;
esac
echo $ar
}
x86_64() { uname -m; }
if_hosttype() { # usage: if_hosttype x64 && echo x64 || echo x86 | BUT, it only fit for intel cpu
case "$HOSTTYPE" in
*x86_64*) sys="x64" ;;
*) sys="x86" ;;
esac
[[ "${sys}" == "$1" ]]
}
#
#
#
# is_git_clean() { git diff-index --quiet --cached HEAD -- 2>/dev/null; }
is_git_clean() { git diff-index --quiet "$@" HEAD -- 2>/dev/null; }
is_git_dirty() {
if is_git_clean "$@"; then
false
else
true
fi
}
git_clone() {
local Deep="--depth=1" Help Dryrun Https Dir arg i=1 Verbose=0
while [[ $# -gt 0 ]]; do
case $1 in
-h | --help)
shift && Help=1
cat <<-EOT
git-clone helps cloneing git repo simply from github/gitlab/bitbucket
Usage: git-clone [-d|--deep] [-s|--https] [-o dir|--dir dir] repo
Description:
git-clone will pull the repo into 'user.repo/', for example:
git-clone hedzr/cmdr
GIT_HOST=gitlab.com git-clone hedzr/cmdr
git-clone [email protected]:hedzr/cmdr.git
git-clone https://github.com/hedzr/cmdr.git
will pull hedzr/cmdr into 'hedzr.cmdr/' directory.
Options and Args:
'--deep' enables full fetch, default is shallow pull only
'--https' enables https protocal, default is ssh protocol
'--dir' specifies the cloned target directory, default is 'user.repo'
'repo' can be these forms:
hedzr/cmdr
https://github.com/hedzr/cmdr
https://github.com/hedzr/cmdr.git
github.com:hedzr/cmdr.git
[email protected]:hedzr/cmdr.git
gitlab.com:hedzr/cmdr
bitbucket.com/hedzr/cmdr
git.sr.ht/hedzr/cmdr
gitee.com/hedzr/cmdr
coding.net/hedzr/cmdr
EnvVars:
GIT_HOSTS extras git hosts such as your own private host
GIT_HOST specify git host explicitly if you're using user/repo form.
EOT
;;
-d | --deep)
# strength=$OPTARG
shift && Deep=""
;;
-dr | --dry-run | --dryrun)
shift && Dryrun=1
;;
-s | --https)
shift && Https=1
;;
-o | --dir | --output)
shift && Dir="$1" && shift
;;
-v | --verbose)
Verbose=1 && shift
;;
*)
case $i in
1)
local Repo="${1:-hedzr/cmdr}"
shift
;;
esac
;;
esac
done
if [[ "$Help" != 1 ]]; then
local Sep='/' Prefix="${GIT_PREFIX:-git@}" Host="${GIT_HOST:-github.com}" h
[[ "$Https" -eq 1 ]] && Prefix="https://"
[[ "$Repo" =~ https://* ]] && Repo="${Repo//https:\/\//}"
for h in github.com gitlab.com bitbucket.com git.sr.ht gitee.com coding.net $GIT_HOSTS; do
[[ "$Repo" =~ $h/* ]] && Host=$h && Repo="${Repo//$h\//}"
[[ "$Repo" =~ $h:* ]] && Host=$h && Repo="${Repo//$h:/}"
done
Repo="${Repo%\#*}"
Repo="${Repo%\?*}"
Repo="${Repo#git@}"
Repo="${Repo%.git}"
Repo="${Repo%/blob/*}"
[[ "$Dir" == "" ]] && Dir="${Repo//\//.}"
[[ "$Prefix" == 'git@' ]] && Sep=':'
local Url="${Prefix}${Host}${Sep}${Repo}.git" Opts=""
(($Verbose)) && Opts="--verbose"
if [[ "$Dryrun" -ne 0 ]]; then
tip "Url: $Url | Deep?: '$Deep' | Opts: '$Opts'"
tip "Result: git clone $Deep -q $Opts "$Url" "$Dir""
else
dbg "cloning from $Url ..." && git clone $Deep -q $Opts "$Url" "$Dir" && {
(($Verbose)) && local DEBUG=1
dbg "git clone $Url DONE."
(($Verbose)) && du -sh "$Dir" || :
}
fi
fi
}
alias git-clone=git_clone
alias git-clone-deep='git_clone -d'
alias git-clone-deep-v='git_clone -d -v'
#
#
url_exists() { curl --head --silent -S --fail --output /dev/null "$@" 1>/dev/null 2>&1; }
#
#
#
headline() { printf "\e[0;1m$@\e[0m:\n"; }
headline_begin() { printf "\e[0;1m"; } # for more color, see: shttps://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux
headline_end() { printf "\e[0m:\n"; } # https://misc.flogisoft.com/bash/tip_colors_and_formatting
printf_black() { printf "\e[0;30m$@\e[0m:\n"; }
printf_red() { printf "\e[0;31m$@\e[0m:\n"; }
printf_green() { printf "\e[0;32m$@\e[0m:\n"; }
printf_yellow() { printf "\e[0;33m$@\e[0m:\n"; }
printf_blue() { printf "\e[0;34m$@\e[0m:\n"; }
printf_purple() { printf "\e[0;35m$@\e[0m:\n"; }
printf_cyan() { printf "\e[0;36m$@\e[0m:\n"; }
printf_white() { printf "\e[0;37m$@\e[0m:\n"; }
h1() { printf "\e[30;104;1m\e[2K\n\e[A%s\e[00m\n\e[2K" "$@"; } # style first header
h2() { printf "\e[30;104m\e[1K\n\e[A%s\e[00m\n\e[2K" "$@"; } # style second header
debug() { in_debug && printf "\e[0;38;2;133;133;133m$@\e[0m\n" || :; }
debug_begin() { printf "\e[0;38;2;133;133;133m"; }
debug_end() { printf "\e[0m\n"; }
dbg() { ((DEBUG)) && printf ">>> \e[0;38;2;133;133;133m$@\e[0m\n" || :; }
tip() { printf "\e[0;38;2;133;133;133m>>> $@\e[0m\n"; }
err() { printf "\e[0;33;1;133;133;133m>>> $@\e[0m\n" 1>&2; }
mvif() {
local src="$1" dstdir="$2"
if [ -d "$dstdir" ]; then
mv "$src" "$dstdir"
fi
}
debug_info() {
debug_begin
cat <<-EOF
in_debug: $(in_debug && echo Y || echo '.')
is_root: $(is_root && echo Y || echo '.')
is_bash: $(is_bash && echo Y || echo '.') # STRICTED = $(is_bash_strict && echo Y || echo N), SHELL = $SHELL, BASH_VERSION = $BASH_VERSION
is_zsh/is_zsh_t1: $(is_zsh && echo Y || echo '.') / $(is_zsh_t1 && echo Y || echo '.') # $(is_zsh && echo "ZSH_EVAL_CONTEXT = $ZSH_EVAL_CONTEXT, ZSH_NAME/VERSION = $ZSH_NAME v$ZSH_VERSION" || :)
is_fish: $(is_fish && echo Y || echo '.') # FISH_VERSION = $FISH_VERSION
in_sourcing: $(in_sourcing && echo Y || echo '.')
if_vagrant/in_vm: $(if_vagrant && echo Y || echo '.') / $(in_vm && echo Y || echo '.')
in_vscode: $(in_vscode && echo Y || echo '.')
in_jetbrains: $(in_jetbrains && echo Y || echo '.')
in_vim/neovim: $(in_vim && echo Y || echo '.') / $(in_neovim && echo Y || echo '.')
darwin/linux/win(wsl): $(is_darwin && echo Y || echo '.')$(is_darwin_sillicon && echo ' [Sillicon] ' || echo ' ')/ $(is_linux && echo Y || echo '.') / $(is_win && echo Y || echo '.')
is_interactive_shell: $(is_interactive_shell && echo Y || echo '.')
NOTE: bash.sh can only work in bash/zsh mode, even if running it in fish shell.
IP(s): 4 -> $(lanip | join_lines), 6 -> $(lanip6 | join_lines)
$(lanipall | pad 9)
Gateway / Mask: $(gw) / $(netmask)
Subnet Prefix: $(subnet4)
EOF
fn_exists pmid && cat <<-EOF
OS tests: pmid='$(pmid)' osid='$(osid)' osidlike='$(osidlike)'
oscodename='$(oscodename)' versionid='$(versionid)' variantid='$(variantid)'
if_nix_typ='$(if_nix_typ)' (\$OSTYPE='$OSTYPE')
is_suse_series='$(is_suse_series && echo Y || echo .)'
EOF
is_linux && cat <<-EOF
lsb_release_cs = '$(lsb_release_cs)'
uname_kernel(-s) = '$(uname_kernel)'
uname_cpu(-p) = '$(uname_cpu)'
uname_mach(-m) = '$(uname_mach)'
uname_rev(-r) = '$(uname_rev)'
uname_ver(-v) = '$(uname_ver)'
i386_amd64 = '$(i386_amd64)'
x86_64 = '$(x86_64)'
if_hosttype = '$(if_hosttype)'
EOF
debug_end
:
}
join_lines() {
local delim="${1:-,}" ix=0
while read line; do
(($ix)) && printf '%s' "$delim"
let ix++
printf '%s' "$line"
done
}
strip_l() { echo ${1#"$2"}; }
strip_r() { echo ${1%"$2"}; }
pad() {
# pad 'pre', 'line' and 'post' as 3-column.
# the 1st arg is the count of indent spaces
# the 2nd and 3rd args are 'pre'-text and 'post'-text
# NOTE that the 'line' itself will be read from stdin.
# sample: cat 1.txt | pad 2
# or: find . -iname '*.log' -print -delete | pad 4 '' ' deleted.'
local line p=$1 && (($#)) && shift
local pre=$1 && (($#)) && shift
local post=$1 && (($#)) && shift
while read line; do printf '%-'$p"s%s%s%s\n" ' ' "$pre" "$line" "$post"; done # <<< "$@"
}
pad3() {
# pad 'pre', 'line' and 'post' as 3-column.
# the 1st arg is the count of indent spaces
# the 2nd arg is the width of 'line'
# the 3rd and 4th args are 'pre'-text and 'post'-text
# NOTE that the 'line' itself will be read from stdin.
# sample: ls -la | pad3 4 '-72' '' ' | desc here'
local line
local p=$1 && (($#)) && shift
local linewidth="${1:--1}" && (($#)) && shift
local pre=$1 && (($#)) && shift
local post=$1 && (($#)) && shift
while read line; do printf '%-'$p"s%s%${linewidth}s%s\n" ' ' "$pre" "$line" "$post"; done # <<< "$@"
}
rpad() {
# sample: rpad 32 - 'Some file' && echo '723 bytes'
# will got:
# Some file-----------------------723 bytes
local cnt=$1
local pad="$(char_repeat $2 $1)"
(($#)) && shift && (($#)) && shift && local y="$@"
# dbg "cnt: $cnt, pad: $pad, y: $y" 1>&2
y="${y:0:$cnt}${pad:0:$((cnt - ${#y}))}"
echo -n "$y"
}
char_repeat() {
# repeat char n times: `char_repeat '-' 32`
local pad=$1 && (($#)) && shift
local n="$1" && (($#)) && shift
printf '%*s' $n "" | tr ' ' "$pad"
}
safety() {
# safety make the folder name more safety when output. It
# replaces $HOME to '~' to prevent home user name leaked.
# In additions, it refers zsh tlide folder name list and
# do the replacements rely on it. That means, if you have
# a zsh hashed folder definition /usr/local/bin -> ~ulbin,
# then it can also be applied to the result of
# $(safety $string).
#
# For example,
#
# $ echo $(./bash.sh safety /home/$USER/Downloads)
# ~/Downloads
# $ echo $(./bash.sh safety $HOME/Downloads)
# ~/Downloads
local input="${@//$HOME/~}" from to list
# dbg "Got input: $input" 1>&2
for list in $HOME/.safety.list; do
if [ -f $list ]; then
while read from to; do
input="$(printf "$input" | sed -E "s,$from,$to,g")"
done <$list
fi
done
if is_zsh_strict; then
# if running under zsh mode
if command -v hash >/dev/null; then
hash -d | while IFS=$'=' read to from; do
from="$(echo $from | tr -d "\042")"
input="$(printf "$input" | sed -E "s,$from,~$to,g")"
done
fi
elif command -v zsh >/dev/null; then
# in bash/sh mode
[ -f /tmp/hash.list ] || zsh -c "hash -d|sed 's/=/:/'|tr -d \"'\"|IFS=\$':' sort -k2 -r" >/tmp/hash.list
while IFS=$':' read to from; do
from="$(eval printf '%s' $from)"
to="$(eval printf '%s' $to)"
# echo " $from -> $to" 1>&2
# echo "$input" | sed -E 's,'"$from"',~'"$to"',g' 1>&2
input="$(printf "$input" | sed -E 's,'"$from"',~'"$to"',g')"
done </tmp/hash.list
fi
# in="$(echo $in | sed -E -e "s,/Volumes/Vol,~vol,g")"
printf "$input"
}
safetypipe() { while read line; do printf "$(safety $line)"; done; }
datename() {
local i=${1:-7}
if [[ $OSTYPE == darwin* ]]; then
date -v-${i}d +%Y-%m-%d
else
date -d -${i}day +%Y-%m-%d
fi
}
for_each_days() {
# Sample:
#
# delete_log_file() {
# local dtname="$1"
# for PRE in .sizes db-bacup tool-updates; do
# $SUDO find . -type f -iname "${PRE}.$dtname"'*'".log" -print -delete | pad 3 "" " deleted."
# done
# }
#
# delete_elder_logs() {
# for_each_days delete_log_file 7 # delete the older logfiles more than 7 days
# }
local func="$1" && (($#)) && shift
local DAYS1="${1:-30}" && (($#)) && shift
local TILLDAYS=365
dbg "func: $func, days: $DAYS1"
# local TILLDAYS=$((DAYS1 + 365))
for ((i = $DAYS1; i < $TILLDAYS; i++)); do
eval $func "$(datename $i)" "$@"
done
}
commander() {
local commander_self="$1" && (($#)) && shift
local commander_cmd="${1:-usage}" && (($#)) && shift
case $commander_cmd in
help | usage | --help | -h | -H) "${commander_self}_usage" "$@" ;;
funcs | --funcs | --functions | --fn | -fn) script_functions "^$commander_self" ;;
*)
# if [ "$(type -t ${commander_self}_${commander_cmd}_entry)" == "function" ]; then
if fn_exists ${commander_self}_${commander_cmd}_entry; then
dbg "try invoking: ${commander_self}_${commander_cmd}_entry | $@"
eval ${commander_self}_${commander_cmd}_entry "$@"
elif fn_exists ${commander_self}-${commander_cmd}-entry; then
eval ${commander_self}-${commander_cmd}-entry "$@"
elif fn_exists ${commander_self}-${commander_cmd}; then
eval ${commander_self}-${commander_cmd} "$@"
elif fn_exists ${commander_self}-${commander_cmd//_/-}; then
eval ${commander_self}-${commander_cmd//_/-} "$@"
elif fn_exists ${commander_self}_${commander_cmd//-/_}; then
eval ${commander_self}_${commander_cmd//-/_} "$@"
else
dbg "try invoking: ${commander_self}_${commander_cmd} | $@"
eval ${commander_self}_${commander_cmd} "$@"
fi
;;
esac
}
script_functions() {
# shellcheck disable=SC2155
local fncs=$(declare -F -p | cut -d " " -f 3 | grep -vE "^[_-]" | grep -vE "\\." | grep -vE "^[A-Z]") # Get function list
if [ $# -eq 0 ]; then
echo "$fncs" # not quoted here to create shell "argument list" of funcs.
else
echo "$fncs" | grep -E "$@"
fi
#declare MyFuncs=($(script.functions));
}
list_all_env_variables() { declare -xp; }
list_all_variables() { declare -p; }
hex2ip4() { local II="$1" && echo "$(((II >> 24) & 0xff)).$(((II >> 16) & 0xff)).$(((II >> 8) & 0xff)).$((II & 0xff))"; }
ip_hex() {
tox() {
local IP S A II
while IFS='/' read IP S; do
is_bash_strict && {
IFS='.' read -ra A <<<"$IP"
II=$(printf '0x%02X%02X%02X%02X' ${A[0]} ${A[1]} ${A[2]} ${A[3]})
echo $II
} || bash <<-EOF
IFS='.' read -ra A <<<"$IP"
II=\$(printf '0x%02X%02X%02X%02X' \${A[0]} \${A[1]} \${A[2]} \${A[3]})
echo \$II
EOF
done
}
lanip | tox
}
netmask_hex() {
tox() {
local IP S M
while IFS='/' read IP S; do
M=$((0xffffffff ^ ((1 << (32 - S)) - 1)))
printf '0x%08x' $M
done
}
lanip | tox
}
subnet_hex() {
tox1() {
# local IP S M A I II
while IFS='/' read IP S; do
is_bash_strict && {
# tip "ip: $IP, S: $S"
M=$((0xffffffff ^ ((1 << (32 - S)) - 1)))
IFS=. read -ra A <<<"$IP"
# tip "A: ${A[@]}, M: $(printf '0x%08x' $M)"
I=$(printf '0x%02X%02X%02X%02X' ${A[0]} ${A[1]} ${A[2]} ${A[3]})
II=$((M & I))
printf '0x%08x' $II
} || bash <<-EOF
M=\$((0xffffffff ^ ((1 << (32 - $S)) - 1)))
IFS=. read -ra A <<<"$IP"
# tip "A: ${A[@]}, M: $(printf '0x%08x' $M)"
I=\$(printf '0x%02X%02X%02X%02X' \${A[0]} \${A[1]} \${A[2]} \${A[3]})
II=\$((M & I))
printf '0x%08x' \$II
EOF
done
}
# tip "lanip: '$(lanip)'"
lanip | tox1
}
if is_darwin; then
readlinkx() {
local p="$@"
[ -L "$@" ] && p="$(readlink "$@")"
echo "$p"
}
realpathx() {
if [[ $1 == /* ]]; then
# dbg " .. case 1: '$1'"
echo "$@"
else
local DIR="${1%/*}" d p
if [ -d "$DIR" ]; then
# dbg " .. case 2: '$1' / DIR = '$DIR' pwd=$(pwd -P)"
DIR="$(cd $DIR && pwd -P)"
d="$DIR/$(basename "$1")"
p="$(readlinkx "$d")"
else
# dbg " .. case 3: '$1'"
p="$(readlinkx "$@")"
fi
# dbg " p: '$p', d: '$d'"
[[ $p == /* ]] && echo "$p" || {
[[ "$p" == "" ]] && echo || {
local DIR="${p%/*}" && {
[ -d "$DIR" ] && { DIR=$(cd $DIR && pwd -P) && echo "$DIR/$(basename $p)"; } || echo "$p"
}
}
}
fi
}
hex2mask() {
local hexmask=$(echo $1 | sed -e 's/^0x//')
local i
# printf "(%s)" $hexmask
for ((i = 0; i < ${#hexmask}; i += 2)); do
if (($i > 1)); then
# use a . to separate octets
# but don't print a leading .
printf "%s" "."
fi
printf "%d" "0x${hexmask:$i:2}"
done
printf "\n"
}
default_dev() { route get default | awk '/interface:/{print $2}'; }
gw() { route get default | awk '/gateway:/{print $2}'; }
lanip() { ifconfig | grep 'inet ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
lanip6() { ifconfig | grep 'inet6 ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
lanipall() { ifconfig | grep -P 'inet6? ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
netmask_hex() { ifconfig $(default_dev) | awk '/netmask /{print $4}'; }
else
ipcmd="$(which ip 1>/dev/null 2>&1 && echo 'sudo ip' || echo ifconfig)"
realpathx() { readlink -f "$@"; }
default_dev() { eval $ipcmd route show default | grep -oE 'dev \w+' | awk '{print $2}'; }
if is_suse_series; then
gw() { which netstat 1>/dev/null 2>&1 && netstat -r -n | grep -P '^0.0.0.0' | awk '{print $2}' || {
if eval "$ipcmd route show" | grep -qP '^default'; then
eval "$ipcmd route show default" | awk '{print $3}'
else
local xx=$(eval "$ipcmd route show" | awk '{print $1}')
if [[ "$xx" = */* ]]; then
cut -d'/' -f1 <<<"$xx" | sed 's/.0$/.1/'
else
echo $xx
fi
fi
}; }
else
gw() { eval "$ipcmd route show default" | awk '{print $3}'; }
fi
lanip() { eval $ipcmd a | grep -E 'inet ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
lanip6() { eval $ipcmd a | grep 'inet6 ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
lanipall() { eval $ipcmd a | grep -E 'inet6? ' | grep -vE '127.0.0.1|::1|%lo|fe80::' | awk '{print $2}'; }
fi
subnet4() { hex2ip4 $(subnet_hex); }
netmask() { hex2ip4 $(netmask_hex); }
# alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'
# alias ip-wan=wanip
wanip() { host myip.opendns.com 208.67.220.222 | tail -1 | awk '{print $4}'; }
wanip6() { host -t AAAA myip.opendns.com resolver1.ipv6-sandbox.opendns.com | grep -oE "^myip\.opendns\.com.*" | awk '{print $5}'; }
# use a tool script 'externalip' is better choice.
# try more sources for yourself:
# http://ipecho.net/plain
# http://ifcfg.me/
# ...
wanip_http() { curl -s http://whatismyip.akamai.com/; }
# the best and exact way is asking a dns server by dig/host:
wanip_exact() { dig @resolver4.opendns.com myip.opendns.com +short; }
wanip6_exact() { dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short -6; }
main_do_sth() {