-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.sh
executable file
·2753 lines (2354 loc) · 97.3 KB
/
util.sh
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
# Author: Awada.Z
# (): string
version() {
echo 7.10.6
}
_U2_Storage_Dir="$HOME/.application"
_U2_Storage_Dir_Quick="$_U2_Storage_Dir/quick"
_U2_Storage_Dir_Bin="$_U2_Storage_Dir/bin"
_U2_Storage_Dir_Trash="$_U2_Storage_Dir/.trash"
# (): number
# default verbose=1, set verbose to something else to suppress logging
if [ -z "$verbose" ] || [ "$verbose" = "true" ] || [ "$verbose" = "1" ]; then verbose="1";
else verbose=""; fi;
# (): string
_SCRIPTPATH() {
echo "$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
}
# eval following line to get the current dir
_PATH() {
echo 'echo "$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"'
}
__dirname() {
exec echo "$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
}
# (): string
_SCRIPTPATHFULL() {
echo "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
}
# eval following line to get the current path
_PATHFULL() {
echo 'echo "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"'
}
_UTILDATE() {
echo $(date +"%Y-%m-%dT%H:%M:%S%z")
}
_PROFILE() {
local profile="$HOME/.bashrc"
if $(os -c mac); then profile="$HOME/.bash_profile"; fi;
echo $profile
}
# (number): number
# return callback, set verbose value to enable
_RC() {
if [ -n "$verbose" ]; then
echo RC, $1, $(basename "$0"), $(_UTILDATE), \<${FUNCNAME[ 1 ]}\>, \("${@:2:$#}"\) >&2
fi;
return $1
}
# (string): number
# error callback, set verbose value to enable
_ERC() {
if [ -n "$verbose" ]; then
echo ERC, 1, $(basename "$0"), $(_UTILDATE), \<${FUNCNAME[ 1 ]}\>, \("${@:2:$#}"\), "<x "$1" x>" >&2
fi;
return 1
}
# (string): string
# echo callback
_EC() {
if [ -n "$verbose" ]; then
echo EC, 0, $(basename "$0"), $(_UTILDATE), \<${FUNCNAME[ 1 ]}\>, \("${@:2:$#}"\), \"\["$1"\]\" >&2
fi;
echo "$@"
}
# (string): string
# echo debug
_ED() {
if [ -n "$verbose" ]; then
echo ED, 0, $(basename "$0"), $(_UTILDATE), \<${FUNCNAME[ 1 ]}\>, \""$@"\" >&2
fi;
}
# echo to file descriptor 2
_E2() {
$@ >&2
}
# Quiet, get rid of descriptor 2
_EQ() {
$@ 2> /dev/null
}
# Quiet, no output
_ENULL() {
$@ > /dev/null 2>&1
}
# (declare -A Option, ...data): {key:value, _:"" }
# example: declare -A data; parseArg data $@; parseGet data _;
parseArg() {
local -n parse_result=$1;
local _target="_";
for i in ${@:2:$#}; do
if ! [[ "$i" =~ ^"-" ]]; then parse_result[$_target]="${parse_result[$_target]}$i ";
else _target=$(echo " $i" | sed 's/^ -*//'); [[ -z "${parse_result[$_target]}" ]] && parse_result[$_target]=' ';
fi;
done;
if [[ -p /dev/stdin ]]; then
while IFS= read -r line; do
parse_result[$_target]=$line
done < /dev/stdin
fi;
}
# (declare -A Option, ...keys): string
parseGet() {
local -n parse_get=$1;
for i in ${@:2:$#}; do if ! [[ -z ${parse_get[$i]} ]]; then _EC "${parse_get[$i]}" && return $(_RC 0 $@); fi; done;
return 1;
}
pathGetFull() {
local path=$(cd "$(dirname "$1")" || exit; pwd)
local file=$(basename "$1")
if [ "$file" = ".." ]; then
_EC "$(dirname "$path")"
else
_EC "$path/$file"
fi
}
trimArgs() {
local joined=""
for str in "$@"; do
joined="$joined$(echo "$str" | xargs)"
done
_EC "$joined"
}
# takes in question, and return 1 as yes, 2 as no, default as 0
prompt() {
local prompter="$@"
read -p "$prompter"$'\n' response
if [[ "$response" =~ [0-9]+ ]]; then
echo $response
else
case "$response" in
[yY]|[yY][eE][sS])
echo 1
;;
[nN]|[nN][oO])
echo 2
;;
*)
echo 0 ;
;;
esac
fi;
}
# unable to receive reference from outside of the script, unless source first
# (PromptString, arrayName)
_promptArray() {
local prompter=$1
local -n options=$2
if ! $(hasValueq ${@:2}); then return $(_ERC "selection collection empty"); fi;
for ((i = 0; i < ${#options[@]}; i++)); do
prompter+=$'\n'"[$i]: ${options[i]}"
done
prompter+=$'\n'"Your Option? Default [0] as ${options[0]}:"
read -p "$prompter"$'\n' responseIndex
if ! $(hasValueq $responseIndex); then
_ED return index [0] as ${options[0]}
echo ${options[0]}
elif ! [[ "$responseIndex" =~ [0-9]+ ]]; then
return $(_ERC "response index not a number");
else
_ED return index [$responseIndex] : ${options[$responseIndex]}
echo ${options[$responseIndex]}
fi;
}
# just read input
promptString() {
local prompter="$@"
read -p "$prompter"$'\n' responseString
echo $responseString
}
# $1:question $2...:select options; i.e. Choose? i1 i2 i3
promptSelect() {
local prompter=$1 options=("${@:2}")
if ! $(hasValueq ${@:2}); then return $(_ERC "selection collection empty"); fi;
for ((i = 0; i < ${#options[@]}; i++)); do
prompter+=$'\n'"[$i]: ${options[i]}"
done
prompter+=$'\n'"Your Option? Default [0] as ${options[0]}:"
read -p "$prompter"$'\n' responseIndex
if ! $(hasValueq $responseIndex); then
_ED return index [0] as ${options[0]}
echo ${options[0]}
elif ! [[ "$responseIndex" =~ [0-9]+ ]]; then
return $(_ERC "response index not a number");
else
_ED return index [$responseIndex] : ${options[$responseIndex]}
echo ${options[$responseIndex]}
fi;
}
# (path): bool
hasDir() {
if [ -d "$1" ]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
# (path): bool
hasFile() {
if [ -f "$1" ]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
# (cmdName): bool
hasCmd() {
if command -v "$1" > /dev/null 2>&1; then
if [[ "$(type -t "$1")" != "function" ]]; then return $(_RC 0 $@); fi;
fi;
return $(_RC 1 $@);
}
# (cmdName): bool
hasCmdq() {
if command -v "$1" > /dev/null 2>&1; then
if [[ "$(type -t "$1")" != "function" ]]; then return 0; fi;
fi;
return 1
}
# (envName): bool
hasEnv() {
if ! [[ -z ${!1+set} ]]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
# (path, ...content): bool
hasContent() {
local path=$1 content="${@:2}"
if ! $(hasFile $path); then return $(_ERC "$path : file not found"); fi;
if $(cat $1 | grep -q "$content"); then return $(_RC 0 "$@"); else return $(_RC 1 "$@"); fi;
}
# (value): bool
hasValue() {
if ! [[ -z $1 ]]; then return $(_RC 0 "$@"); else return $(_RC 1 "$@"); fi;
}
# hasValue quiet
hasValueq() {
! [[ -z $1 ]]
}
has() {
declare -A has_data; parseArg has_data $@;
if [ "$_target" = "_" ]; then
return $(! [[ -z $1 ]]);
fi;
parseGetQ() {
local -n parse_get=$1;
for i in ${@:2:$#}; do if ! [[ -z ${parse_get[$i]} ]]; then echo "${parse_get[$i]}" && return 0; fi; done;
return 1;
}
local cmd=$(parseGet has_data c cmd command);
local cmdQ=$(parseGetQ has_data C Cmd Command);
local dir=$(parseGet has_data d dir);
local dirQ=$(parseGetQ has_data D Dir);
local file=$(parseGet has_data f file);
local fileQ=$(parseGetQ has_data F File);
local path=$(parseGet has_data p path);
local pathQ=$(parseGetQ has_data P Path);
local env=$(parseGet has_data e env);
local envQ=$(parseGetQ has_data E Env);
local help=$(parseGet has_data help);
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-c,--cmd \t (string) \t check if it has command\n'
helpmsg+='\t-C,--Cmd \t (string) \t check if it has command quietly\n'
helpmsg+='\t-d,--dir \t (string) \t check if it has directory\n'
helpmsg+='\t-D,--Dir \t (string) \t check if it has directory quietly\n'
helpmsg+='\t-f,--file \t (string) \t check if it has file\n'
helpmsg+='\t-F,--File \t (string) \t check if it has file quietly\n'
helpmsg+='\t-p,--path \t (string) \t check if it has path, both dir or file\n'
helpmsg+='\t-P,--Path \t (string) \t check if it has path quietly, both dir or file\n'
helpmsg+='\t-e,--env \t (string) \t check if it has environment\n'
helpmsg+='\t-E,--Env \t (string) \t check if it has environment quietly\n'
cmd_has() {
if ! [[ -z "$(command -v $1)" ]]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
cmd_Q_has() {
! [[ -z "$(command -v "$1")" ]];
}
dir_has() {
if [ -d "$@" ]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
dir_Q_has() {
[ -d "$@" ];
}
file_has() {
if [ -f "$@" ]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
file_Q_has() {
[ -f "$@" ];
}
path_has() {
if [ -e "$@" ]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
path_Q_has() {
[ -e "$@" ];
}
env_has() {
if ! [[ -z ${!1+set} ]]; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
}
env_Q_has() {
! [[ -z ${!1+set} ]];
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$cmd"); then cmd_has $cmd;
elif $(hasValueq "$cmdQ"); then cmd_Q_has $cmdQ;
elif $(hasValueq "$dir"); then dir_has $dir;
elif $(hasValueq "$dirQ"); then dir_Q_has $dirQ;
elif $(hasValueq "$file"); then file_has $file;
elif $(hasValueq "$fileQ"); then file_Q_has $fileQ;
elif $(hasValueq "$path"); then path_has $path;
elif $(hasValueq "$pathQ"); then path_Q_has $pathQ;
elif $(hasValueq "$env"); then env_has $env;
elif $(hasValueq "$envQ"); then env_Q_has $envQ;
fi;
}
# (envName, ?replacement): string | null
envGet() {
if $(hasEnv $1); then _EC "${!1}"; else _EC "$2"; fi;
}
# -s,--size,_ *_default
# -m,--modify modify date
# -M,--modifyQ modify date quiet output long
# -f,--full full info
stat() {
declare -A stats_data; parseArg stats_data $@;
local size=$(parseGet stats_data s size _);
local modify=$(parseGet stats_data m modify);
local modifyQ=$(parseGet stats_data M modifyQ)
local full=$(parseGet stats_data f full);
local help=$(parseGet stats_data help);
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-s,--size,_ \t (string) \t size of the path\n'
helpmsg+='\t-m,--modify \t (string) \t modify date of the path\n'
helpmsg+='\t-M,--modifyQ \t (string) \t modify date of the path as long, quiet\n'
helpmsg+='\t-f,--full \t (string) \t full stats info\n'
unset -f stat;
STAT=$(which stat);
size_stats() {
_EC $(du -sh $1 | cut -f1)
}
modify_stats() {
if $(os -c mac); then _EC $($STAT -f "%Sm" -t "%Y-%m-%d %H:%M:%S" $1);
else _EC $($STAT --printf="%y\n" $1 | awk -F'[ .]' '{print $1, $2}'); fi;
}
modifyQ_stats() {
# os -c mac quiet
if $(hasCmdq uname && uname | grep -q Darwin); then
$STAT -f "%Sm" -t "%s" $1
else
formatDate=$($STAT --printf="%y\n" "$1" | awk -F'[ .]' '{print $1, $2}')
date -d "$formatDate" +%s
fi;
}
full_stats() {
size_stats $1
modify_stats $1
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$size"); then size_stats $size;
elif $(hasValueq "$modify"); then modify_stats $modify;
elif $(hasValueq "$modifyQ"); then modifyQ_stats $modifyQ;
elif $(hasValueq "$full"); then full_stats $full;
fi;
}
# -c,--check,_ *_default
# -p,--pkgmanager
# -i,--info
# -s,--sys
os() {
declare -A os_data; parseArg os_data $@;
local check=$(parseGet os_data c check _);
local pkgmanager=$(parseGet os_data p pkgmanager);
local info=$(parseGet os_data i info);
local sysinfo=$(parseGet os_data s sys);
local bashinfo=$(parseGet os_data b bash);
local help=$(parseGet os_data help);
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-c,--check,_ \t\t (string) \t check os trait fit current os\n'
helpmsg+='\t-p,--pkgmanager \t () \t\t get current package manager\n'
helpmsg+='\t-i,--info \t\t () \t\t get os info, including hardware\n'
helpmsg+='\t-s,--sys \t\t () \t\t get system info, with cpu, mem and disk info\n'
helpmsg+='\t-b,--bash \t\t () \t\t get bash info, with active one and installed one\n'
# (): string
pkgManager_os() {
if $(hasCmd yum); then _EC "yum";
elif $(hasCmd brew); then _EC "brew";
elif $(hasCmd apt); then _EC "apt";
elif $(hasCmd apk); then _EC "apk";
elif $(hasCmd pacman); then _EC "pacman";
elif $(hasCmd dnf); then _EC "dnf";
elif $(hasCmd choco); then _EC "choco";
elif $(hasCmd winget); then _EC "winget";
else _EC "NONE";
fi;
}
# (osTrait): bool
check_os() {
case $1 in
mac | darwin | macos | apple | osx | brew)
if $(hasCmdq uname && uname | grep -q Darwin); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
centos | yum)
if $(hasCmdq yum); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
alpine | apk)
if $(hasCmdq apk); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
debian | deb | dpkg)
if $(hasCmdq dpkg); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
ubuntu | apt)
if $(hasCmdq apt-get); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
arch | archlinux | pacman )
if $(hasCmdq pacman); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
redhat | dnf | rhel)
if $(hasCmdq dnf); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
linux)
if $(hasCmdq uname) && uname | grep -q Linux; then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
win | windows)
if $(echo "$OSTYPE" | grep -q msys || echo "$OSTYPE" | grep -q cygwin); then return $(_RC 0 $@); else return $(_RC 1 $@); fi;
;;
*)
if [ "$OSTYPE" = "$1" ]; then return $(_RC 0 $@);
else return $(_ERC "Error: not listed, this is actual ostype: $OSTYPE");
fi;
;;
esac
}
info_os() {
echo Package Manager: $(pkgManager_os);
if $(hasCmdq uname); then uname -a; fi;
if [ -f "/etc/os-release" ]; then cat /etc/os-release; fi;
if $(hasCmdq wmic); then wmic os get Caption, Version, BuildNumber; fi;
# hardware, CPU, GPU, MEM, DISK
if $(hasCmdq systeminfo); then systeminfo; return; fi;
if $(hasCmdq system_profiler); then system_profiler SPSoftwareDataType SPHardwareDataType SPDisplaysDataType SPSerialATADataType; return; fi;
if $(hasCmdq lshw); then lshw -short | cat; fi;
}
sys_os() {
if $(os -c mac); then
df -hP;
top -l 1 | head -n 10
elif $(os -c linux); then
df -Th --exclude-type=overlay;
top -bn1 | head -n 6
elif $(os -c win); then
wmic logicaldisk get name,size,freespace
wmic cpu get LoadPercentage
wmic memorychip get Capacity,Speed,Manufacturer,ConfiguredClockSpeed
fi;
}
bash_os() {
echo -e Session bash: "\t" $(echo $BASH_VERSION);
echo -e System bash: "\t" $(bash --version | head -n 1);
_ED use 'ln $(which bash) /bin/bash' to use the new bash
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$check"); then check_os $check;
elif $(hasValueq "$pkgmanager"); then pkgManager_os $pkgmanager;
elif $(hasValueq "$sysinfo"); then sys_os $sysinfo;
elif $(hasValueq "$bashinfo"); then bash_os $bashinfo;
elif $(hasValueq "$info"); then info_os $info;
fi;
}
# (): string
uuid() {
local B C='89ab'
local N=0
while [ "$N" -lt 16 ]; do
B=$(( $RANDOM%256 ))
case $N in
6) printf '4%x' $(( B%16 )) ;;
8) printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 )) ;;
3 | 5 | 7 | 9) printf '%02x-' $B ;;
*) printf '%02x' $B ;;
esac
N=$(( N + 1 ))
done
echo
}
# -p,--public (route_number) Public ip *_default
# -4,--ipv4 () bool, use ipv4 to connect to internet *_default
# -6,--ipv6 () bool, use ipv6 to connect to internet
# -P,--private () private ip
ip() {
declare -A ip_data; parseArg ip_data $@;
local public=$(parseGet ip_data p public _);
local private=$(parseGet ip_data P private);
local ipv4=$(parseGet ip_data 4 ipv4);
local ipv6=$(parseGet ip_data 6 ipv6);
local help=$(parseGet ip_data help);
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-p,--public,_ \t (4/6) \t ipv4 / ipv6, display public ip\n'
helpmsg+='\t-4,--ipv4 \t () \t use ipv4 to connect to internet\n'
helpmsg+='\t-6,--ipv6 \t () \t use ipv6 to connect to internet\n'
helpmsg+='\t-P,--private \t () \t display private ip\n'
# ():string
ipLocal() {
local ethernet wifi
if $(os -c linux); then
unset -f ip;
IP=$(which ip);
ethernet=$($IP addr show eth1 2> /dev/null | grep "inet\b" | awk '{print $2}' | cut -d/ -f1)
wifi=$($IP addr show eth0 2> /dev/null | grep "inet\b" | awk '{print $2}' | cut -d/ -f1)
if $(hasValue $ethernet); then _ED ethernet && _EC $ethernet;
elif $(hasValue $wifi); then _ED wifi && _EC $wifi;
else _ED ip && _EC $($IP route get 1.2.3.4 | awk '{print $7}' | head -1); fi;
elif $(os -c mac);then
ethernet=$(ipconfig getifaddr en1)
wifi=$(ipconfig getifaddr en0)
if $(hasValue $ethernet); then _ED ethernet && _EC $ethernet;
else _ED wifi && _EC $wifi; fi;
fi;
}
get2() {
local url=$1 version=$2 wgetArg="--inet4-only --prefer-family=IPv4" curlArg="--ipv4"
if $(string -e "$version" 6); then wgetArg="--inet6-only --prefer-family=IPv6" curlArg="--ipv6"; fi;
if $(hasCmd wget); then wget -qO- $wgetArg "$url";
elif $(hasCmd curl); then curl -s -X $curlArg GET "$url";
fi;
echo ""
}
# (route_number):string
ipPublic() {
iv=4
if $(hasValueq "$ipv6"); then iv=6; fi;
case $1 in
2) _ED ipinfo.io/ip with ipv$iv && _EC $(get2 ipinfo.io/ip $iv) ;;
3) _ED api.ipify.org with ipv$iv && _EC $(get2 api.ipify.org $iv) ;;
4) _ED ifconfig.me with ipv$iv && _EC $(get2 ifconfig.me $iv) ;;
*) _ED ident.me with ipv$iv && _EC $(get2 ident.me $iv) ;;
esac
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$public"); then ipPublic $public;
elif $(hasValueq "$private"); then ipLocal $private;
else ipPublic $public;
fi;
}
dates() {
declare -A date_data; parseArg date_data $@;
local parse=$(parseGet date_data p parse _)
local dateTime=$(parseGet date_data D Datetime);
local dateLong=$(parseGet date_data l long);
local dateOnly=$(parseGet date_data d date);
local timeOnly=$(parseGet date_data t time);
local plain=$(parseGet date_data P plain);
local iso=$(parseGet date_data i iso);
local full=$(parseGet date_data f full)
local older=$(parseGet date_data o older)
local help=$(parseGet date_data help);
local dateFormat='%Y-%m-%d'
local timeFormat='%H:%M:%S'
local dateTimeFormat='%Y-%m-%d %H:%M:%S'
local dateLongFormat='%s'
local plainFormat='%Y_%m_%d_%H_%M_%S'
local iso8601="%Y-%m-%dT%H:%M:%S%z"
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-p,--parse,_ \t\t () \t\t parse date from string, can use "now"\n'
helpmsg+='\t-D,--Datetime, \t\t () \t\t date as datetime format\n'
helpmsg+='\t-l,--long \t\t () \t\t date as long format\n'
helpmsg+='\t-d,--date \t\t () \t\t date only format of date\n'
helpmsg+='\t-t,--time \t\t () \t\t time only format of date\n'
helpmsg+='\t-P,--plain \t\t () \t\t plain format of date\n'
helpmsg+='\t-f,--full \t\t () \t\t full display format of date\n'
helpmsg+='\t-o,--older \t\t (time1, time2?, gap?) \t time2 can be "now", if gap exist, use absolute num for diff\n'
if $(hasCmdq gdate); then DATE=$(which gdate);
else DATE=$(which date); fi;
parse_dates() {
local input=$(echo $@ | xargs)
plainFormat="[0-9]+_[0-9]+_[0-9]+_[0-9]+_[0-9]+_[0-9]+"
longFormat="^[0-9]+$"
now="now"
if [[ $input =~ $plainFormat ]]; then input=$(echo "$input" | awk -F_ '{printf("%s-%s-%s %s:%s:%s", $1, $2, $3, $4, $5, $6)}');
elif [[ $input =~ $longFormat ]]; then echo $input;
elif [[ $input =~ $now ]]; then date +%s;
else $DATE -d "$input" +%s;
fi;
}
if ! $(hasValueq $parse); then time=$(date +%s);
else time=$(parse_dates $parse); fi;
if ! $(hasValueq $time); then return $(_ERC "time parsing error"); fi;
toFormat_dates() {
echo $($DATE -d "@$time" +"$1")
}
older_dates() {
shift
value1="$1"
value2="$2"
gap="$3"
_ED value1 {$value1} value2 {$value2} gap {$gap}
if ! $(hasValueq $value2); then
return $(_ERC "value 1 missing")
fi;
if ! $(hasValueq $value2); then
_ED "value2 missing, using current time";
value2=$time
fi;
value1=$(parse_dates $value1);
value2=$(parse_dates $value2);
difference=$(($value1 - $value2));
if $(hasValueq $gap); then
_ED gap {$gap} found, using absolute number
difference=${difference#-}
if [ "$difference" -gt $gap ]; then _RC 0 difference:$difference '>' $gap;
else _RC 1 difference:$difference '<=' $gap;
fi;
elif [ "$difference" -gt 0 ]; then _RC 0 difference:$value1 '>' $value2;
else _RC 1 difference:$value1 '<=' $value2; fi;
}
full_dates() {
_ED "-D,Datetime" "$dateTimeFormat"
toFormat_dates "$dateTimeFormat";
_ED "-l,long" "$dateLongFormat"
toFormat_dates "$dateLongFormat";
_ED "-d,date" "$dateFormat"
toFormat_dates "$dateFormat";
_ED "-t,time" "$timeFormat"
toFormat_dates "$timeFormat";
_ED "-p,plain" "$plainFormat"
toFormat_dates "$plainFormat";
_ED "-i,iso" "$iso8601"
toFormat_dates "$iso8601";
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$dateTime"); then toFormat_dates "$dateTimeFormat";
elif $(hasValueq "$dateLong"); then toFormat_dates "$dateLongFormat";
elif $(hasValueq "$dateOnly"); then toFormat_dates "$dateFormat";
elif $(hasValueq "$timeOnly"); then toFormat_dates "$timeFormat";
elif $(hasValueq "$plain"); then toFormat_dates "$plainFormat";
elif $(hasValueq "$iso"); then toFormat_dates "$iso8601";
elif $(hasValueq "$older"); then older_dates "$@";
elif $(hasValueq "$full"); then full_dates $full;
else toFormat_dates "$dateTimeFormat";
fi;
}
# -p,--path path to trash, *_default
# -l,--list list trash
# -i,--index get path from index
# -r,--restore restore file
# -c,--clean clean trash older than 3 month
# -d,--delete delete one
# -P,--purge rm all files from trash dir
trash() {
declare -A trash_data; parseArg trash_data $@;
declare -A folder_data;
local path=$(parseGet trash_data p path _);
local list=$(parseGet trash_data l list);
local indexDir=$(parseGet trash_data i index);
local restore=$(parseGet trash_data r restore);
local clean=$(parseGet trash_data c clean);
local delete=$(parseGet trash_data d delete);
local purge=$(parseGet trash_data P purge);
local help=$(parseGet trash_data help);
local helpmsg="${FUNCNAME[0]}:\n"
helpmsg+='\t-p,--path,_ \t (string) \t move target path to trash path\n'
helpmsg+='\t-l,--list \t (string) \t list infos on current input path, default to list all\n'
helpmsg+='\t-i,--index \t (number) \t input index number and get target trash dir\n'
helpmsg+='\t-r,--restore \t (string) \t restore folder depends on current path\n'
helpmsg+='\t-c,--clean \t (number) \t clean trash older than 3 month, default 7890000 \n'
helpmsg+='\t-d,--delete \t () \t choose a trash and delete it \n'
helpmsg+='\t-P,--purge \t () \t\t remove all trash from trash path\n'
local TP="$_U2_Storage_Dir_Trash"
local trashInfoName="_U2_TRASH_INFO"
put_trash() {
local input=$@
if ! $(hasValueq $input); then return $(_ERC "to trash path not specified"); fi;
local inputPath=$(pathGetFull $input)
if ! $(has --Path $inputPath); then return $(_ERC "input path {$inputPath} not exist"); fi;
local uid="$(uuid)"
local trashDir=$(trimArgs $TP / $uid)
local size=$(du -sh $inputPath | awk '{print $1}')
local infoDir=$(trimArgs $trashDir / $trashInfoName)
mkdir -p $trashDir
mv -fv $inputPath $trashDir
printf "uuid=$uid \noriginalDir=$inputPath \ndtime=$(date +'%Y-%m-%d %H:%M:%S')\nsize=$size\n" > $infoDir
}
loadArray() {
readarray -t folders < <(ls -lt "$TP" | tail -n +2 | awk '{print $9}')
folder_data[length]=${#folders[@]}
for ((i=0; i<${#folders[@]}; i++)); do
folder=${folders[i]}
info_file=$(trimArgs $TP / $folder / $trashInfoName)
while IFS= read -r line; do
folder_data["${i}_index"]=$i
if [[ $line == "uuid="* ]]; then
folder_data[${i}_uuid]=${line#"uuid="}
elif [[ $line == "originalDir="* ]]; then
folder_data[${i}_original_dir]=${line#"originalDir="}
elif [[ $line == "dtime="* ]]; then
folder_data[${i}_dtime]=${line#"dtime="}
elif [[ $line == "size="* ]]; then
folder_data[${i}_size]=${line#"size="}
fi
done < "$info_file"
done
}
# call loadArray() beforehand, $1:index, $2: eval condition
trashFilter() {
local indexStr=$1
local evalStr=$2
local length=${folder_data[length]}
for ((i=0; i<$length; i++)); do
target=${folder_data[${i}_${indexStr}]}
if ! $(eval "$evalStr \"$target\""); then
unset folder_data[${i}_index]
unset folder_data[${i}_uuid]
unset folder_data[${i}_original_dir]
unset folder_data[${i}_dtime]
unset folder_data[${i}_size]
fi;
done
}
# $1 eval if condition
printTrashList(){
printf 'index:\tOriginal Directory:\t\t\t\t\tDeletetime:\t\tSize:\tDIR:\n'
local length=${folder_data[length]}
for ((i=0; i<$length; i++)); do
uuid=${folder_data[${i}_uuid]}
if ! $(hasValueq $uuid); then continue; fi;
index=${folder_data[${i}_index]}
original_dir=${folder_data[${i}_original_dir]}
dtime=${folder_data[${i}_dtime]}
size=${folder_data[${i}_size]}
printf "$index\t$original_dir\t\t$dtime\t$size\t$(echo $TP/$uuid | xargs)\n"
done
}
list_trash() {
local dir=$1
loadArray
if ! $(hasValueq $dir); then
printTrashList
else
dir=$(pathGetFull $dir)
trashFilter "original_dir" 'a(){ if $(echo $1 | grep -q'" $dir); then return 0; else return 1; fi; }; a"
printTrashList
fi;
}
restore_trash() {
local dir=$1
if ! $(hasValueq $dir); then dir="."; fi;
loadArray
dir=$(pathGetFull $dir)
trashFilter "original_dir" 'a(){ if $(echo $1 | grep -q'" $dir); then return 0; else return 1; fi; }; a"
printTrashList
if [ ${#folder_data[@]} -lt 2 ]; then
return $(_ERC "Error: empty, nothing to restore in $dir");
fi;
response=$(prompt "which one to restore ? [index:0]")
if ! $(hasValueq ${folder_data[${response}_uuid]}); then return $(_ERC "index:$response does not exit"); fi;
uuid=${folder_data[${response}_uuid]}
original_dir=${folder_data[${response}_original_dir]}
targetTrashDir=$(trimArgs $TP / $uuid)
mv $(trimArgs $targetTrashDir / $trashInfoName) /tmp
mv -i $(trimArgs $targetTrashDir "/*") "$(dirname "$original_dir")"
}
delete_trash() {
local dir=$1
if ! $(hasValueq $dir); then dir="."; fi;
loadArray
dir=$(pathGetFull $dir)
trashFilter "original_dir" 'a(){ if $(echo $1 | grep -q'" $dir); then return 0; else return 1; fi; }; a"
printTrashList
if [ ${#folder_data[@]} -lt 2 ]; then
return $(_ERC "Error: empty, nothing to restore in $dir");
fi;
response=$(prompt "which one to delete ? [index:0]")
if ! $(hasValueq ${folder_data[${response}_uuid]}); then return $(_ERC "index:$response does not exit"); fi;
uuid=${folder_data[${response}_uuid]}
targetTrashDir=$(trimArgs $TP / $uuid);
rm -rf $targetTrashDir
}
index_trash() {
loadArray
length=${folder_data[length]}
if ! $(hasValueq $1); then return $(_ERC "need target index"); fi;
if [ $1 -gt $length ]; then echo "."; return $(_ERC "index [$1] larger than total length [$length]"); fi;
for ((i=0; i<$length; i++)); do
if [ "${folder_data[${i}_index]}" = "$1" ]; then
_EC $(trimArgs $TP / ${folder_data[${i}_uuid]});
return
fi;
done
}
clean_trash() {
local seconds=7890000
if $(hasValueq $1); then seconds=$1; fi;
loadArray
trashFilter "dtime" 'a(){ if $(dates -o "$@" "now"'" $seconds); then return 0; else return 1; fi; }; a "
printTrashList
if [ "${#folder_data[@]}" -lt 2 ]; then
return $(_RC 0 "Info: No available file found")
fi
response=$(prompt "clean these content in $TP ? (no) ")
if [ $response -ne 1 ]; then
return $(_RC 0 "clean not performed, exit clean")
fi;
length=${folder_data[length]}
for ((i=0; i<$length; i++)); do
if $(hasValueq ${folder_data[${i}_uuid]}); then
rmTarget=$(trimArgs $TP / $uuid)
_ED removing $rmTarget
rm -rf $rmTarget
fi;
done
_ED clean complete
}
purge_trash() {
local response=$(prompt "purge all content in $TP ? (no) ")
if [ $response -ne 1 ]; then
return $(_RC 0 "purge not performed, exit purge")
fi;
rm -rf $TP;
mkdir -p $TP;
_ED purge complete
}
if $(hasValueq "$help"); then printf "$helpmsg";
elif $(hasValueq "$path"); then put_trash $path;
elif $(hasValueq "$list"); then list_trash $list;
elif $(hasValueq "$restore"); then restore_trash $restore;
elif $(hasValueq "$indexDir"); then index_trash $indexDir;
elif $(hasValueq "$clean"); then clean_trash $clean;
elif $(hasValueq "$delete"); then delete_trash $delete;
elif $(hasValueq "$purge"); then purge_trash $purge;
fi;
}
# (...?pkgname)
## package update, or general update
upgrade() {
local prefix="" m=$(os -p)
if $(os -c linux) && $(hasCmd sudo); then prefix="sudo"; fi;
if ! $(hasValue $@); then
_ED update packages list
if [ "$m" = "yum" ]; then eval $(_EC "$prefix yum update -y");
elif [ "$m" = "brew" ]; then eval $(_EC "brew update");
elif [ "$m" = "apt" ]; then eval $(_EC "$prefix DEBIAN_FRONTEND=noninteractive apt-get update -y");
elif [ "$m" = "apk" ]; then eval $(_EC "$prefix apk update");
elif [ "$m" = "pacman" ]; then eval $(_EC "$prefix pacman -Sy");
elif [ "$m" = "dnf" ]; then eval $(_EC "$prefix dnf check-update");
elif [ "$m" = "choco" ]; then eval $(_EC "choco upgrade all -y");
elif [ "$m" = "winget" ]; then eval $(_EC "winget upgrade --all -y --accept-package-agreements --accept-source-agreements");
fi;
else
if [ "$m" = "yum" ]; then eval $(_EC "$prefix yum upgrade -y $@");
elif [ "$m" = "brew" ]; then eval $(_EC "brew install $@");
elif [ "$m" = "apt" ]; then eval $(_EC "$prefix DEBIAN_FRONTEND=noninteractive apt-get upgrade -y $@");
elif [ "$m" = "apk" ]; then eval $(_EC "$prefix apk upgrade $@");
elif [ "$m" = "pacman" ]; then eval $(_EC "$prefix pacman -Syu --noconfirm $@");
elif [ "$m" = "dnf" ]; then eval $(_EC "$prefix dnf upgrade -y $@");
elif [ "$m" = "choco" ]; then eval $(_EC "choco upgrade -y $@");
elif [ "$m" = "winget" ]; then eval $(_EC "winget upgrade --accept-package-agreements --accept-source-agreements $@");
fi;
fi;
}
# (...pkgname): string
install() {
local prefix="" m=$(os -p)
if $(os -c linux) && $(hasCmd sudo); then prefix="sudo"; fi;
if [ "$m" = "yum" ]; then eval $(_EC "$prefix yum install -y $@");