-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path.bash_functions
2276 lines (2198 loc) · 61.2 KB
/
.bash_functions
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
# vim: ft=bash noet:
! declare 2>&1 | \grep -wq ^colors= && [ $BASH_VERSINFO -ge 4 ] && source $initDir/.colors
test "$debug" -gt 0 && echo "=> Running $bold${colors[blue]}$(basename ${BASH_SOURCE[0]})$normal ..."
Source $initDir/.bash_functions.build
Source $initDir/.bash_functions.AV
test "$debug" -gt 0 && Echo "\n=> \${BASH_SOURCE[*]} = ${BASH_SOURCE[*]}\n"
find="$(type -P find)"
function EchoSpecialCharacters {
local rc=$?
set +o histexpand # Turn off history expansion to be able easily use the exclamation mark in strings i.e https://stackoverflow.com/a/22130745/5649639
command echo "$@"
set -o histexpand
return $rc
}
function Cat {
local highlightCMD="command highlight -O ansi --force"
if [ $# = 0 ] || [ "$1" = - ];then
$highlightCMD
else
for file
do
echo "::::::::::::::" 1>&2
echo $file 1>&2
echo "::::::::::::::" 1>&2
$highlightCMD "$file"
done
fi
}
function Less {
local highlightCMD="command highlight -O ansi --force"
local extension=not_yet_defined
local lessColors="command less -R"
local less="command less -r"
if [ $# = 0 ] || [ "$1" = - ];then
$highlightCMD | $lessColors
else
for file
do
extension=$(basename "$file" | awk -F"." '{print tolower($NF)}')
[ $extension != pdf ] && $highlightCMD "$file" | $lessColors || $less "$file"
done
fi
}
function More {
local highlightCMD="command highlight -O ansi --force"
if [ $# = 0 ] || [ "$1" = - ];then
$highlightCMD
else
for file
do
echo "::::::::::::::" 1>&2
echo $file 1>&2
echo "::::::::::::::" 1>&2
$highlightCMD "$file"
done
fi | more
}
function Most {
local highlightCMD="command highlight -O ansi --force"
if [ $# = 0 ] || [ "$1" = - ];then
$highlightCMD | most
else
for file
do
echo "::::::::::::::" 1>&2
echo $file 1>&2
echo "::::::::::::::" 1>&2
$highlightCMD "$file" | most
done
fi
}
function Nohup {
local firstArg=$1
local nohup="command nohup"
if [ $(type -t $firstArg) = function ]
then
shift && $nohup bash -c "$(declare -f $firstArg);$firstArg $*"
elif [ $(type -t $firstArg) = alias ]
then
alias nohup='\nohup '
eval "nohup $@"
else
$nohup "$@"
fi
}
function Sudo {
local firstArg=$1
if [ $(type -t $firstArg) = function ]
then
shift && $sudo bash -c "$(declare -f $firstArg);$firstArg $*"
elif [ $(type -t $firstArg) = alias ]
then
alias sudo='\sudo '
eval "sudo $@"
else
$sudo "$@"
fi
}
function Top {
local top=$(type -aP top | \grep ^/usr) #Au cas ou il y a un script top ailleurs dans le PATH
local processPattern=$1
test -n "$processPattern" && shift && local processPIDs=$(\pgrep -f $processPattern)
if [ -z "$processPIDs" ]
then
$top
else
if [ $osFamily = Linux ]
then
$top -d 1 $(printf -- "-p %d " $processPIDs) $@
elif [ $osFamily = Darwin ]
then
$top -i 1 $(printf -- "-pid %d " $processPIDs) $@
fi
fi
}
function addUsersInGroup {
# local lastArg="$(eval echo \${$#})"
# local lastArg="${@:$#}"
local lastArg="${@: -1}"
local allArgsButLast="${@:1:$#-1}"
for user in $allArgsButLast
do
sudo adduser $user $lastArg
done
}
function anyTimeWithTZ2LocalTimeZone {
local remoteTime=to_be_defined
local remoteTZ=to_be_defined
local destinationTZ
local date=date
local localTZ=$(date +%Z | sed 's/ST$/T/')
test $osFamily = Darwin && date=gdate
if [ $# = 0 ];then
echo "=> Usage : $FUNCNAME remoteTime [destinationTZ=$localTZ]" >&2
return 1
elif [ $# = 1 ];then
case $1 in
-h|--h|-help|--help) echo "=> Usage : $FUNCNAME remoteTime [destinationTZ=$localTZ]" >&2;return 1;;
*) remoteTime=${1/./:};destinationTZ=$localTZ;;
esac
else
remoteTime=${1/./:}
destinationTZ=${2/%ST/T}
fi
remoteTZ=$(echo $remoteTime | awk '{printf$NF}')
case $remoteTZ in
AT) remoteTZ=$(TZ=Canada/Atlantic date '+%Z')
remoteTime=${remoteTime/ AT/ $remoteTZ};;
CT) remoteTZ=$(TZ=US/Central date '+%Z')
remoteTime=${remoteTime/ CT/ $remoteTZ};;
ET) remoteTZ=$(TZ=US/Eastern date '+%Z')
remoteTime=${remoteTime/ ET/ $remoteTZ};;
PT) remoteTZ=$(TZ=US/Pacific date '+%Z')
remoteTime=${remoteTime/ PT/ $remoteTZ};;
AET) remoteTZ=$(TZ=Australia/Sydney date '+%Z')
remoteTime=${remoteTime/ AET/ $remoteTZ};;
CET) remoteTZ=$(TZ=CEST date '+%Z')
remoteTime=${remoteTime/ CET/ $remoteTZ};;
*) ;;
esac
TZ=$destinationTZ $date -d "$remoteTime"
}
function any2ascii {
local encoding=unknown
for file
do
encoding=$(file -b -i "$file" | cut -d= -f2 | $sed "s/([0-9]+)[lb]e/\1/")
if type -P iconv >/dev/null 2>&1;then
iconv -f $encoding "$file"
elif type -P recode >/dev/null 2>&1;then
cat "$file" | recode $encoding.. 2>/dev/null
fi
done
}
function apkInfo {
type aapt >/dev/null || return
local apkFullInfo="$(type -P aapt) dump badging"
for package
do
echo "=> package = $package"
[ -f "$package" ] || {
echo "==> ERROR : The file $package does not exist." >&2; continue
}
$apkFullInfo "$package"
echo
done | egrep "^$|\b([s]dkVersion|application-label|native-code|versionName|package: +name)[:=][^ ]+"
}
function apkRename {
type aapt >/dev/null || return
local apkFullInfo="$(type -P aapt) dump badging"
for package
do
echo "=> package = $package"
[ -f "$package" ] || {
echo "==> ERROR : The package $package does not exist." >&2; continue
}
packagePath=$(dirname "$package")
set -o pipefail
packageID=$($apkFullInfo "$package" | awk -F"'" '/^package:/{print$2}') || continue
set +o pipefail
packageVersion=$($apkFullInfo "$package" | awk -F"'" '/^package:/{print$6}' | cut -d' ' -f1)
packageNewFileName="$packagePath/$packageID-$packageVersion.apk"
[ "$package" = $packageNewFileName ] || \mv -vi "$package" $packageNewFileName
done
}
function apkRename_All_APKs {
type aapt || return
ls *.apk >/dev/null && apkRename *.apk
}
function aria2c {
# local options="$(echo "$@" | \sed -E "s/(^| )[^ -]+\b//g")" # Suppressing non options
# local urls="$(echo "$@" | \sed -E "s/(^| )-[^ ]+\b//g")" # Suppressing options
# for url in $urls
for url
do
command aria2c $options "$url"
done
}
function asc2gpg {
for ascFile
do
\gpg -v -o "${ascFile/.asc/.gpg}" --dearmor "$ascFile"
done
}
function aslookup {
echo "AS | IP | BGP Prefix | CC | Registry | Allocated | AS Name"
for ip
do
whois -h whois.cymru.com " -v $ip" | \grep ^[0-9]
done
}
function aslookupSeb {
local options=""
if echo $1 | grep "^-" -q;then
options="$1 $2"
shift 2
fi
echo "AS | IP | BGP Prefix | CC | Registry | Allocated | AS Name"
for ip
do
whois $ip | awk -v ip=$ip -F':| +' 'BEGIN{IGNORECASE=1}/Origin(AS)?:/{as=$3}/CIDR:|route:/{cidr=$3}/country:/{country=$3}/RegDate:/{regdate=$3}/netname:/{asname=$3}END{printf "%-7s | %-16s | %-19s | %-2s | %-8s | %-10s | %s\n", as,ip,cidr,country,registry,regdate,asname}'
done
}
function awkCalc {
set -- ${@/[/(}
set -- ${@/]/)}
\awk -v CONVFMT=%.15g 'BEGIN{ print '"$*"' "" }'
}
function backupFile {
for file
do
date=$(stat -c %y "$file" | cut -d" " -f1 | tr -d -)
ext="${file/*./}"
basename="${file/*\//}"
basename="${basename/.$ext/}"
\cp -piv "$file" "$basename-$date.$ext"
done
}
function baseName {
for arg
do
echo ${arg/*\//}
done
}
function bible {
local bible="command bible"
for verses
do
$bible $verses | sed -n "2,3p"
$bible -f $verses | cut -d: -f2
done
}
function brewInstall {
if ! type -P brew >/dev/null 2>&1; then
if [ $osFamily = Linux ]; then
if groups | \egrep -wq "adm|admin|sudo|wheel";then
brewPrefix=/home/linuxbrew/.linuxbrew
else
brewPrefix=$HOME/.linuxbrew
fi
elif [ $osFamily = Darwin ]; then
brewPrefix=/usr/local
fi
$SHELL -c "$(\curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" || return
echo $PATH | grep -q $brewPrefix || export PATH=$brewPrefix/bin:$PATH
brew=$brewPrefix/bin/brew
$brew -v
fi
if test -x $brew;then
source $initDir/.bash_functions.brew
brewPostInstall
fi
}
function brewPortableInstall {
brew=undefined
brewPrefix=undefined
if ! type -P brew > /dev/null 2>&1; then
git --help >/dev/null || return
brewPrefix=$HOME/.linuxbrew
git clone https://github.com/homebrew/brew $brewPrefix
echo $PATH | grep -q $brewPrefix || export PATH=$brewPrefix/bin:$PATH
brew=$brewPrefix/bin/brew
$brew -v
fi
if test -x $brew;then
source $initDir/.bash_functions.brew
brewPostInstall
fi
}
function castnowPlaylist {
test $# = 0 && {
echo "=> Usage: $FUNCNAME [index] [format] playlistFile ..." >&2
return 1
}
local index=1
local format="mp4[height<=480]/mp4/best"
local playlist
test $# = 1 && playlist=$1
test $# = 2 && format=$1 && playlist=$2
test $# = 3 && index=$1 && format=$2 && playlist=$3
printf "=> Start playing playlist at: "
\sed -n "${index}p" $playlist
castnowURLs $format $(awk '{print$1}' $playlist | \grep -v "^#" | tail -n +$index)
}
function castnowURLs {
test $# = 0 && {
echo "=> Usage: $FUNCNAME [ytdl-format] url1 url2 ..." >&2
return 1
}
local format="mp4[height<=480]/mp4/best"
echo $1 | \egrep -q "^(https?|s?ftps?)://" || { format="$1"; shift; }
for url
do
echo "youtube-dl --no-continue --ignore-config -f $format -o- -- $url | castnow --quiet -"
youtube-dl --no-continue --ignore-config -f "$format" -o- -- "$url" | castnow --quiet -
done
set +x
echo
}
function cgrep {
local allArgsButLast="${@:1:$#-1}"
local lastArg="${@: -1}"
local url="$lastArg"
if [ $# == 0 ]
then
echo "=> Usage: $FUNCNAME [grepOptions] regexp url"
return 1
fi
\curl -Ls "$url" | grep $allArgsButLast
}
function chromium_snap_start {
local SNAP=$(snap run --shell chromium -c 'echo $SNAP')
local SNAP_USER_COMMON=$(snap run --shell chromium -c 'echo $SNAP_USER_COMMON')
SNAP=$SNAP SNAP_USER_COMMON=$SNAP_USER_COMMON $SNAP/bin/chromium.launcher "$@" &
}
function cleanFirefoxLock {
case $osID in
debian) firefoxProgramName=iceweasel;;
ubuntu) firefoxProgramName=firefox;;
esac
pgrep -lf $firefoxProgramName || \rm -vf ~/.mozilla/firefox/*.default/lock ~/.mozilla/firefox/*.default/.parentlock
}
function compareRemoteFile {
local sdiffOptions=""
if [ $# != 3 ] && [ $# != 4 ];then
echo "=> Usage: $FUNCNAME filePath server1|localhost|. server2|localhost|." >&2
return 1
elif [ $# == 4 ] && [ ${1:0:1} == "-" ];then
sdiffOptions=$1
shift
[ ${sdiffOptions:0:2} == "-h" ] && sdiff --help && return
fi
local filePath="$1"
shift
local server1=$1
local server2=$2
#Le dernier cat est la au cas ou le mdp est demande de maniere interactive
if [ $server1 = localhost ] || [ $server1 == . ];then
sdiff $sdiffOptions "$filePath" <(ssh $server2 cat "$filePath") | cat
elif [ $server2 = localhost ] || [ $server2 == . ];then
sdiff $sdiffOptions <(ssh $server1 cat "$filePath") "$filePath" | cat
else
sdiff $sdiffOptions <(ssh $server1 cat "$filePath") <(ssh $server2 cat "$filePath") | cat
fi
}
function compareRemoteDir {
local sdiffOptions=""
if [ $# != 3 ] && [ $# != 4 ];then
echo "=> Usage: $FUNCNAME dirPath server1|localhost|. server2|localhost|." >&2
return 1
elif [ $# == 4 ] && [ ${1:0:1} == "-" ];then
sdiffOptions=$1
shift
[ ${sdiffOptions:0:2} == "-h" ] && sdiff --help && return
fi
local dirPath="$1"
shift
local server1=$1
local server2=$2
#Le dernier cat est la au cas ou le mdp est demande de maniere interactive
if [ $server1 = localhost ] || [ $server1 == . ];then
sdiff $sdiffOptions <(find "$dirPath" -printf '%p\t%s\n' | sort) <(ssh $server2 find "$dirPath" -printf '"%p\t%s\n"' | sort) | cat
elif [ $server2 = localhost ] || [ $server2 == . ];then
sdiff $sdiffOptions <(ssh $server1 find "$dirPath" -printf '"%p\t%s\n"' | sort) <(find "$dirPath" -printf '%p\t%s\n' | sort) | cat
else
sdiff $sdiffOptions <(ssh $server1 find "$dirPath" -printf '"%p\t%s\n"' | sort) <(ssh $server2 find "$dirPath" -printf '"%p\t%s\n"' | sort) | cat
fi
}
function conda2Rename {
oldName=$1
newName=$2
test $# = 2 && {
conda2 create --name $newName --offline --clone $oldName
conda2 remove --name $oldName --offline --all
}
}
function conda3Rename {
oldName=$1
newName=$2
test $# = 2 && {
conda3 create --name $newName --offline --clone $oldName
conda3 remove --name $oldName --offline --all
}
}
function condaSearchThroughChannels {
pythonChannelsList="conda-forge intel anaconda aaronzs"
for pkg
do
for ch in $pythonChannelsList
do
echo "=> Searching through conda channel <$ch> ..."
conda search -c $ch $pkg 2>/dev/null
done
done
}
function convertion {
local lastArg="${@: -1}"
local retCode=unset
set -o pipefail
units -t "$@" | tr -d "\n"
retCode=$?
set +o pipefail
echo " $lastArg"
return $retCode
}
function countWorkDays {
local monthNumber=-1
local year=-1
case $# in
0) monthNumber=$(date +%m);year=$(date +%Y);;
1) test $1 -le 12 && { monthNumber=$1;year=$(date +%Y);} || year=$1;;
2) monthNumber=$1;year=$2;;
*) echo "=> Usage: $FUNCNAME [monthNumber=current] [year=current]" >&2;return 1;;
esac
# export LC_MESSAGES=en_US.UTF-8
if [ $# == 1 ] && [ $monthNumber == -1 ];then
gcal -Hno -b1 $year | \egrep -v "^Sa|^Su|$year|^$|^ +[[:alpha:]]+" | sed "s/^[[:alpha:]]*\s*//g" | fmt -w 1 | wc -l
else
gcal -Hno $monthNumber $year | \egrep -v "Saturday|Sunday|$year|^$" | sed "s/^[[:alpha:]]*\s*//g" | fmt -w 1 | wc -l
fi
}
function createSshTunnel {
test $# -lt 3 && {
echo "=> Usage : $FUNCNAME <localPort> <remotePort> <remoteServer> <sshServer>"
echo "OR"
echo "=> Usage : $FUNCNAME <localPort> <remotePort> <sshServer>"
return 1
} >&2
declare -i localPort=$1
declare -i remotePort=$2
if [ $# = 3 ]
then
declare sshServer=$3
remoteServer=localhost
elif [ $# -gt 3 ]
then
declare remoteServer=$3
declare sshServer=$4
test $sshServer = $remoteServer && remoteServer=localhost
fi
if autossh -V >/dev/null 2>&1
then
# command autossh -M 0 -f -T -N cli-myJupyter-Tunnel
command autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -f -N -L $localPort:$remoteServer:$remotePort $sshServer
else
command ssh -f -N -L $localPort:$remoteServer:$remotePort $sshServer
fi
pgrep ssh.*-L
}
function ddPV {
test $# -lt 2 && {
echo "=> Usage: $FUNCNAME if=FILE of=FILE OPTIONS ..." >&2
return -1
}
input=$1
inputFile=$(echo $input | awk -F= '{print$2}')
shift
#echo "=> sudo pv --wait $inputFile | sudo dd $@ ..."
#time sudo pv --wait $inputFile | sudo dd $@
echo "=> sudo bash -c \"pv $inputFile | dd $@\" ..."
time sudo bash -c "pv $inputFile | dd $@"
}
function dfc {
firstArg=$1
if echo "$firstArg" | \egrep -q "^\-|^$"
then
command dfc -TWfc always "$@"
else
shift
test $# != 0 && argsRE="|$(echo "$@" | tr -s / | sed 's/ /$|/g' | sed "s,/$,," | sed 's/$/$/')"
firstArg=$(echo "$firstArg" | tr -s /)
test "$firstArg" != / && firstArg="$(echo "$firstArg" | sed "s,/$,,")"
command dfc -TWfc always | sed "s/ *$//" | \egrep "FILESYSTEM|${firstArg}\>${argsRE}"
fi
}
function dirName {
#NE MARCHE PAS LORSQUE LE CHEMIN NE CONTIENT PAS DE "/"
for arg
do
echo ${arg%/*}
done
}
function distribName {
local osName=unknown
echo $OSTYPE | grep -q android && local osFamily=Android || local osFamily=$(uname -s)
if [ $osFamily = Linux ]; then
if grep -w ID /etc/os-release -q 2>/dev/null; then
osName=$(source /etc/os-release && echo $ID)
elif [ -s /etc/issue.net ]; then
osName=$(awk '{print tolower($1)}' /etc/issue.net)
elif ! lsb_release -si 2>/dev/null | grep -i "n/a" -q; then
osName=$(lsb_release -si | awk '{print tolower($0)}')
elif type -P hostnamectl >/dev/null 2>&1; then
osName=$(hostnamectl status | awk '/Operating System/{print tolower($3)}')
fi
elif [ $osFamily = Darwin ]; then
osName="$(sw_vers -productName)"
elif [ $osFamily = Android ]; then
osName=Android
elif [ $osFamily = VMkernel ]; then # ESXi
osName=ESXi
else
test -n $OSTYPE && osName=$OSTYPE || osName=$osFamily
fi
echo $osName | awk '{print tolower($0)}'
}
function distribType {
local distribType=unknown
echo $OSTYPE | grep -q android && local osFamily=Android || local osFamily=$(uname -s)
if [ $osFamily = Linux ]; then
if grep ID_LIKE /etc/os-release -q 2>/dev/null; then
distribType=$(source /etc/os-release && echo $ID_LIKE)
elif [ ls /etc/*_version >/dev/null 2>&1 ]; then
distribType=$(echo /etc/*version | sed 's,/etc/\|_version,,g')
else
distribName=$(distribName)
case $distribName in
sailfishos|rhel|fedora|centos) distribType=redhat ;;
ubuntu) distribType=debian;;
*) distribType=$distribName ;;
esac
fi
elif [ $osFamily = Darwin ]; then
distribType=Darwin
elif [ $osFamily = Android ]; then
distribType=Android
elif [ $osFamily = VMkernel ]; then # ESXi
distribType=ESXi
else
test -n $OSTYPE && distribType=$OSTYPE || distribType=$osFamily
fi
echo $distribType
}
function envSorted {
command env "$@" | sort
}
function expandURL {
for url
do
time \curl -sIL "${url}" | sed -n 's/[Ll]ocation: *//p'
done
}
function extractURLsFromFiles {
for file
do
\sed -E 's/^.*http/http/;s/[<"].*$//;/^\s*$/d;/http/!d' "$file"
done | sort -u
}
function extractURLsFromFiles_Simplified {
for file
do
\grep -oP '(www|http:|https:)+[^\s"]+[\w]' "$file" | uniq
done | sort -u
}
function extractURLsFromURLs {
for url
do
\curl -Ls "$url" | \sed -E 's/^.*http/http/;s/[<"].*$//;/^\s*$/d;/http/!d'
done | sort -u
}
function extractURLsFromURLs_Simplified {
for url
do
\curl -Ls "$url" | \grep -oP '(www|http:|https:)+[^\s"]+[\w]' | uniq
done | sort -u
}
function fileTypes {
[ $osFamily = Darwin ] && local find=gfind
time for dir
do
$find $dir -xdev -ls | awk '{print substr($3,1,1)}' | sort -u
done
}
function findSeb {
[ $osFamily = Darwin ] && local find=gfind
local dir=$1
if echo $dir | \grep -q "^-"
then
dir=.
else
shift
fi
# firstPredicate=$1
# shift
local args=("$@")
if echo "${args[@]}" | \grep -q "\-ls"
then
args=( "${args[@]/-ls/}" )
$find $dir $firstPredicate ${args[@]} -printf "%10i %10k %M %n %-10u %-10g %10s %AY-%Am-%Ad %.12AX %p\n"
else
$find $dir $firstPredicate ${args[@]}
fi
}
function findCorruptedFilesIn {
local grep=$(type -P ggrep 2>/dev/null || type -P grep)
time $grep -a -r . "$@" >/dev/null
}
function findWithHumanReadableSizes {
[ $osFamily = Darwin ] && local find=gfind
local dir=$1
echo $dir | \grep -q "\-" && dir=. || shift
local args=("$@")
if echo "${args[@]}" | \grep -q "\-ls"
then
$find $dir $firstPredicate "${args[@]}" | numfmt --field 7 --from=iec --to=iec-i --suffix=B | \column -t
else
$find $dir $firstPredicate "${args[@]}"
fi
}
function findLoops {
echo $OSTYPE | \grep android -q && local osFamily=Android || local osFamily=$(uname -s)
[ $osFamily = Darwin ] && local find=gfind
time $find "$@" -xdev -follow -printf ""
}
function fsUsage {
local df="command df"
local filesytem=/
if [ $# = 0 ];then
filesytem=/
elif [ $# = 1 ];then
filesytem=$1
fi
$df -m $filesytem | awk '/dev/{printf " Usage of %s: %.1f%% of %.2fGB\n", $NF, 100*$3/$2, $2/1024}'
}
function functionDefinition {
[ $osFamily = Darwin ] && local sed="command sed -E"
[ $osFamily = Linux ] && local sed="command sed -r"
type "$@" | \grep -v 'is a function$' | $sed 's/(;| )$//;s/ /\t/g'
}
function gdebiALL {
for package
do
sudo gdebi -n $package
done
}
function getCertificate {
for url
do
url="${url#http*\/\/}"
url="${url/\/*/}"
openssl s_client -showcerts -verify 5 -connect "$url":https </dev/null 2>/dev/null | openssl x509
done
}
function getBJC {
#bjcUrl=http://www.bibledejesuschrist.org/downloads/bjc_internet.pdf
bjcUrl=http://www.bibledejesuschrist.org/downloads/bjc.pdf
extension=${bjcUrl/*./}
bjcBaseName=$(basename $bjcUrl .$extension)
echo "=> Downloading last BJC version ..."
wget $bjcUrl
\mv -v $bjcBaseName.$extension "${bjcBaseName}_$(date -d "$(stat -c %y $bjcBaseName.$extension)" +%Y%m%d_%HH%MM%S).$extension"
}
function getCodeName {
if [ $# != 2 ];then
echo "=> Usage: $FUNCNAME brand model" >&2
return 1
fi
local brand=$1
local model=$2
local curl="command curl -sL"
local codeNameJSONDataBaseURL=https://github.com/jaredrummler/AndroidDeviceNames/raw/master/json/manufacturers
if $curl -I $codeNameJSONDataBaseURL/$brand.json | \grep "Not Found";then
echo "[$FUNCNAME] => ERROR : The page $codeNameJSONDataBaseURL/$brand.json was not found." >&2
return 2
fi
$curl $codeNameJSONDataBaseURL/$brand.json | jq -r --arg model $model '.devices[] | select( .model | match($model;"i") ).codename'
}
function getField {
test $# -ne 3 && {
echo "=> ERROR on Usage: $FUNCNAME separator1 separator2 fieldNumber" >&2
return 1
}
local sep1="$1"
local sep2="$2"
declare -i fieldNumber=$3
awk -F "${sep1}|$sep2" "{print\$$fieldNumber}"
}
function getFiles {
test $# -lt 2 && {
echo "=> Usage: $FUNCNAME <wget args> URL" >&2
return 1
}
local lastArg="$(eval echo \${$#})"
local baseUrl=$(echo $url | awk -F/ '{print$3}')
local wget="command wget"
local url=$lastArg
echo $url | egrep "^(https?|ftp)://" || {
echo "=> ERROR: This protocol is not supported by GNU Wget." >&2
return 2
}
# time $wget --no-parent --continue --timestamping --random-wait --user-agent=Mozilla --content-disposition --convert-links --page-requisites --recursive --reject index.html --accept "$@"
set -x
time $wget --no-parent --continue --timestamping --random-wait --user-agent=Mozilla --content-disposition --convert-links --page-requisites --recursive --accept "$@"
set +x
}
function getPythonFunctionName {
local funcName=$1
shift
test $# != 0 && grepParagraph "def $funcName " '^$' $@
}
function getPythonFunctions {
test $# != 0 && grepParagraph "def " '^$' $@
}
function getShellFunctionName {
local funcName=$1
shift
test $# != 0 && grepParagraph "(^|\s)$funcName\s*\(\)|\bfunction\s$funcName" '^}' $@
}
function getShellFunctions {
test $# != 0 && grepParagraph '(^|\s)\w+\(\)|\bfunction\b' '^}' $@
}
function getURLTitle {
for url
do
printf "$url # " >&2
if type -P xidel >/dev/null;then
xidel -s --css 'head title' "$url"
elif type -P pup >/dev/null;then
\curl -Ls "$url" | pup --charset utf8 'head title text{}'
fi
done
}
function getVideosFromRSSPodCastPlayList {
test $# = 1 && {
local rssURL="$1"
local wget="$(type -P wget2 2>/dev/null || type -P wget)"
# $wget $(youtube-dl -g "$rssURL")
$wget $(curl -s "$rssURL" | egrep -o "https?:[^ <>]*(mp4|webm)" | grep -v .google.com/ | uniq)
}
}
function gpg2asc {
for gpgFile
do
\gpg -o - --enarmor "$gpgFile" | sed "s/ARMORED FILE/PUBLIC KEY BLOCK/" | tee "${gpgFile/.gpg/.asc}"
done
}
function gpgPrint {
for pubKey
do
echo $pubKey
printf -- "-%.s" $(seq ${#pubKey})
echo
\gpg $pubKey | awk '{printf$1" "$2" "$3"\n""uid\t\t ";$1=$2=$3="";print}'
echo
done
}
function grepdoc {
local pattern="$1"
shift
for doc
do
catdoc "$doc" | egrep -H --label="$doc" -i "${pattern}"
done
}
function grepFunction {
test $# -lt 2 && {
echo "=> Usage : $FUNCNAME startRegExpPattern fileList" >&2
return 1
}
echo $1 | grep -q -- "^-[a-z]" && local option=$1 && shift
local startRegExpPattern=$1
shift
grepParagraph $option "function $startRegExpPattern|${startRegExpPattern}.*[(]" "^}" "$@"
}
function grepParagraph {
set +x
local fileListPattern="-"
test $# -lt 2 && {
echo "=> Usage : $FUNCNAME [-h|-l] startRegExpPattern endRegExpPattern [fileList]" >&2
return 1
}
test $# = 2 && {
echo "=> Calling $FUNCNAME through pipe is not yes implemented. " >&2
return 2
}
echo $1 | grep -q -- "^-[a-z]" && local option=$1 && shift
fileListPattern="${@:3}"
local startRegExpPattern
local endRegExpPattern
# startRegExp=$1 endRegExp=$2 \sed -E -n "/$startRegExpPattern/,/$endRegExpPattern/p" $fileListPattern
# startRegExp=$1 endRegExp=$2 awk "/$startRegExpPattern/{p=1}p;/$endRegExpPattern/{p=0}" $fileListPattern
case $option in
-h) startRegExp=$1 endRegExp=$2 perl -ne 'print "$_" if /$ENV{startRegExp}/ ... (/$ENV{endRegExp}/ || eof)' $fileListPattern
;;
-l) startRegExp=$1 endRegExp=$2 perl -ne 'print "$ARGV\n" if /$ENV{startRegExp}/ ... (/$ENV{endRegExp}/ || eof)' $fileListPattern | uniq
;;
*) startRegExp=$1 endRegExp=$2 perl -ne 'print "$ARGV:$_" if /$ENV{startRegExp}/ ... (/$ENV{endRegExp}/ || eof)' $fileListPattern
;;
esac
}
function grepSection {
test $# -lt 2 && {
echo "=> Usage : $FUNCNAME startRegExpPattern fileList" >&2
return 1
}
echo $1 | grep -q -- "^-[a-z]" && local option=$1 && shift
local startRegExpPattern=$1
shift
grepParagraph $option "$startRegExpPattern" "^$" "$@"
}
function greplast {
grep "$@" | awk 'END{print}'
}
function h5L {
local switch="$1"
echo $switch | \grep -q "^-" && shift 1 || switch=""
for file
do
\h5ls -r $switch $file
done | \egrep "Group|Attribute:|Dataset|Data:"
}
function help {
local help="builtin help"
local lines=$($help "$@" | wc -l)
local termLines=$(tput lines)
[ $lines -gt $termLines ] && $help "$@" | less || $help "$@"
}
function hide {
for file
do
mv $file .$file
done
}
function html2pdf {
test $# = 0 && {
echo "=> Usage: $FUNCNAME url_or_file1 url_or_file1 ..." >&2
return 1
}
if ! type -P wkhtmltopdf >/dev/null 2>&1;then
echo "=> ERROR[$FUNCNAME]: You need to install the <wkhtmltopdf> tool." >&2
return 2
fi
local pdfFiles=""
local pageSize=$(paperconf)
for url_or_file
do
pdfFileName=$(basename $url_or_file | \sed -E "s/#.*|[)]//;s/%20|[(]/_/g;s/$|\.[^.]+$/.pdf/")
pdfFiles+="$pdfFileName "
wkhtmltopdf --page-size $pageSize --minimum-font-size 12 --no-background --outline --header-line --footer-line --header-left [webpage] --footer-left "[isodate] [time]" --footer-right [page]/[toPage] "$url_or_file" "$pdfFileName"
done
echo
echo "=> OutputFile = $pdfFileName"
echo
open $pdfFiles
}
function htmlReIndent {
test $# = 1 && [ $1 = - ] && xmllint --html --format - && return
for file
do
xmllint --html --format "$file" 2>/dev/null > "${file/.*/.indented.html}"
[ $? != 0 ] && echo "=> WARNING: xmllint could not re-indent $file." >&2 && continue
\mv -v "${file/.*/.indented.html}".indented "$file"
done | sort -u
}
function httpLocalServer {
# local fqdn=$(host $(hostname) | awk '/address/{print$1}')
# local fqdn=$(\dig +short -x $(\dig +search +short $(hostname)))
local fqdn=localhost
local ip=$(\dig -x +search +short $(hostname))
local -i port=1234
local python="command python"
case $1 in
-h|-help|--h|--help) echo "=> Usage: $FUNCNAME [portNumber|$port]" >&2; return 1 ;;
esac
test $1 && port=$1
if [ $port -lt 1024 ] && [ $UID != 0 ]; then
echo "=> ERROR: Only root can bind to a tcp port lower than 1024." >&2
return 2
fi
local pythonVersion="$($python -V 2>&1 | sed 's/[A-Za-z]* //' | cut -d. -f1)"
case $pythonVersion in
2) SimpleHTTPServerModuleName=SimpleHTTPServer;;
3) SimpleHTTPServerModuleName=http.server;;
esac
local oldPort=$(\ps -fu $USER | \grep -v awk | awk "/$SimpleHTTPServerModuleName/"'{print$NF}')
\ps -fu $USER | \grep -v grep | \grep -q $SimpleHTTPServerModuleName && echo "=> $SimpleHTTPServerModuleName is already running on http://$fqdn:$oldPort/" || {
logfilePrefix=$SimpleHTTPServerModuleName_$(date +%Y%m%d)
mkdir -p ~/log
nohup $python -m $SimpleHTTPServerModuleName $port >~/log/${logfilePrefix}.log 2>&1 &
test $? = 0 && {
echo "=> $SimpleHTTPServerModuleName started on http://$ip:$port/" >&2
echo "=> logFile = ~/log/${logfilePrefix}.log" >&2
}
}
}
function hw-probeAddNodeToInventory {
local inventoryID=null
if ! type -P hw-probe >/dev/null 2>&1;then
echo "=> ERROR [$FUNCNAME] : You must first install <hw-probe>." >&2
return 1
fi
if [ $# = 0 ];then
inventoryID="LHW-8028-0102-D496-15BF"
elif [ $# = 1 ] && [ $1 != -h ] && [[ $1 =~ /[A-Z0-9-]+/ ]];then
inventoryID=$1
else
echo "=> $FUNCNAME [inventoryID]" >&2
return 2
fi
[ -n "$sudo" ] && sudo="sudo -E"
local architecture=$(uname)
test $architecture = Darwin && architecture=bsd
hwprobe=$(which hw-probe)
time $sudo $hwprobe -all -upload -i $inventoryID && echo "=> INFO: Check your email to add confirm adding the new node to your inventory : https://$architecture-hardware.org/index.php?view=computers&inventory=$inventoryID" >&2
}
function img2pdfA4 {