-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathusual_JBs.sh
executable file
·1756 lines (1497 loc) · 79.9 KB
/
usual_JBs.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
#!/bin/bash
#
# Autor= João Batista Ribeiro
# Bugs, Agradecimentos, Críticas "construtivas"
# me envie um e-mail. Ficarei Grato!
# e-mail: [email protected]
#
# Este programa é um software livre; você pode redistribui-lo e/ou
# modifica-lo dentro dos termos da Licença Pública Geral GNU como
# publicada pela Fundação do Software Livre (FSF); na versão 2 da
# Licença, ou (na sua opinião) qualquer versão.
#
# Este programa é distribuído na esperança que possa ser útil,
# mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a
# qualquer MERCADO ou APLICAÇÃO EM PARTICULAR.
#
# Veja a Licença Pública Geral GNU para mais detalhes.
# Você deve ter recebido uma cópia da Licença Pública Geral GNU
# junto com este programa, se não, escreva para a Fundação do Software
#
# Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# Script: usual / common day-to-day functions general
#
# Last update: 13/07/2024
#
useColor() {
#BLACK='\e[1;30m'
RED='\e[1;31m'
GREEN='\e[1;32m'
NC='\033[0m' # reset/no color
BLUE='\e[1;34m'
#PINK='\e[1;35m'
CYAN='\e[1;36m'
#WHITE='\e[1;37m'
}
notUseColor() {
#unset BLACK RED GREEN NC BLUE PINK CYAN WHITE
unset RED GREEN NC BLUE CYAN
}
emptySpaces=$1 # Remove empty space form calls in this script to itself with $colorPrint empty
if [ "$emptySpaces" == '' ]; then
shift
fi
colorPrint=$1
if [ "$colorPrint" == "noColor" ]; then # Colors disabled
shift
else # Some colors for script output - Make it easier to follow
useColor
colorPrint=''
fi
notPrintHeaderHeader=$1
if [ "$notPrintHeaderHeader" != "notPrintHeader" ]; then
echo -e "$BLUE #___ Script to usual commands ___#$NC\n"
else
shift
fi
testColorInput=$1
if [ "$testColorInput" == "testColor" ]; then
#echo -e "\n Test colors: $BLACK BLACK $RED RED $GREEN GREEN $NC NC $BLUE BLUE $PINK PINK $CYAN CYAN $WHITE WHITE\n"
echo -e "\n Test colors: $RED RED $GREEN GREEN $NC NC $BLUE BLUE $CYAN CYAN\n"
shift
fi
optionInput=$1
case $optionInput in
"date-up" )
echo -e "$CYAN# Update the date #$NC"
dateUpFunction() { # Need to be run as root
ntpVector=("pool.ntp.org" "ntp1.ptb.de" "ntp.usp.br" "200.20.186.75" "bonehed.lcs.mit.edu") # Ntp servers
#${#ntpVector[*]} # size of ntpVector
#${ntpVector[$i]} # value of the $i index in ntpVector
#${ntpVector[@]} # all value of the vector
tmpFileNtpError=$(mktemp) # Create a tmp file
timeUpdated="false"
for ntpValue in "${ntpVector[@]}"; do # Run until flagContinue is false and run the break or ntpVector get his end
echo -e "\nRunning: ntpdate -u -b $ntpValue"
ntpdate -u -b "$ntpValue" 2> "$tmpFileNtpError" # Run ntpdate with one value of ntpVector and send the errors to a tmp file
if ! grep -q -v "no server" "$tmpFileNtpError"; then # Test if ntpdate got error "no server suitable for synchronization found"
if ! grep -q -v "time out" "$tmpFileNtpError"; then # Test if ntpdate got error "time out"
if ! grep -q -v "name server cannot be used" "$tmpFileNtpError"; then # Test if can name resolution works
echo -e "\n${CYAN}Time updated:$GREEN $(date)$NC"
timeUpdated="true" # Set true in the timeUpdated
break
fi
fi
fi
done
if [ "$timeUpdated" == "false" ]; then
echo -e "\nSorry,$RED time not updated$NC: $(date)"
if grep -q "name server cannot be used" "$tmpFileNtpError"; then # Test if can name resolution works
echo -e "\nError:$RED No connection found$NC - Check your network connection"
fi
fi
#cat $tmpFileNtpError
rm "$tmpFileNtpError" # Delete the tmp file
}
export -f dateUpFunction
export CYAN NC GREEN RED
if [ "$(whoami)" != "root" ]; then
echo -e "$CYAN\nInsert the root Password to continue$NC"
fi
su root -c 'dateUpFunction' # In this case without the hyphen (su - root -c 'command') to no change the environment variables
# It's advisable that users acquire the habit of always following the su command with a space and then a hyphen
# The hyphen: (1) switches the current folder to the home folder of the new user (e.g., to /root in the case of the root user) and
# (2) it changes the environmental variables to those of the new user
# If the first argument to su is a hyphen, the current folder and environment will be changed to what would be expected if the new user had actually
# logged on to a new session (rather than just taking over an existing session)
;;
"--help" | "-h" | "help" | 'h' | '' | 'w' )
if [ "$optionInput" == '' ] || [ "$optionInput" == 'w' ]; then # whiptailMenu()
notUseColor
fi
# Options text
optionVector=("audio-extract " " - Extract audio from a video file"
"brigh-1 " "$RED * - Set brightness percentage value (accept % value, up and down)"
"brigh-2 " "$BLUE = - Set brightness percentage value with xbacklight (accept % value, up, down, up % and down %)"
"brigh-3 " "$BLUE = - Set brightness percentage value with xrandr (accept value, l, m, h, up and down)"
"check-pkg-i " " - Check if all packages in a folder (and subfolders) are installed"
"cpu-max " " - Show the 10 process with more CPU use"
"date-up " "$RED * - Update the date"
"day-s-i " "$RED * - The day the system was installed"
"file-equal " " - Look for equal files using md5sum in the current folder (and subfolders)"
"folder-diff " " - Show the difference between two folders and (can) make them equal (with rsync)"
"folder-equal" " - Look for equal files in \"folder2\" that are in \"folder1\" using md5sum"
"git-gc " " - Run git gc (|--auto|--aggressive) in the subfolders"
"git-up " " - Run git pull and force update to the local files (deleting changes) with the remote in the subfolders"
"help " " - Show this help message (the same result with \"help\", \"--help\", \"-h\" or 'h')"
"ip " " - Get your IP"
"kill " " - Search for program with pattern/name and (can) kill it"
"l-pkg-i " " - List the last package(s) installed (accept 'n', where 'n' is a number of packages, the default is 10)"
"l-pkg-r " " - List the last package(s) removed (accept 'n', where 'n' is a number of packages, the default is 10)"
"l-pkg-u " " - List the last package(s) upgrade (accept 'n', where 'n' is a number of packages, the default is 10)"
"mem-info " " - Show memory and swap percentage of use"
"mem-max " " - Show the 10 process with more memory RAM use"
"mem-use " " - Get the all (shared and specific) use of memory RAM from one process/pattern"
"mtr-test " "$RED * - Run a mtr-test on a domain (default is google.com)"
"pdf-r " " - Reduce a PDF file"
"ping-test " " - Run a ping-test on a domain (default is google.com)"
"pkg-count " " - Count of packages that are installed your Slackware"
"pkg-i " "$RED * - Install package(s) from a folder (and subfolders) in the Slackware"
"pkg-r " "$RED * - Remove package(s) from a folder (and subfolders) in the Slackware"
"pkg-u " "$RED * - Upgrade package(s) from a folder (and subfolders) in the Slackware"
"print-lines " " - Print part of file (lineStart to lineEnd)"
"s-pkg-f " " - Search in the installed package folder (/var/log/packages/) for one pattern (-f of fast)"
"s-pkg-s " " - Search in the installed package folder (/var/log/packages/) for one pattern (-r of summary files)"
"screenshot " " - Screenshot from display :0"
"search-pwd " " - Search in this folder (recursive) for a pattern"
"shred " " - shred files in local folder (and subfolders)"
"slack-up " "$RED * - Slackware update"
"sub-extract " " - Extract subtitle from a video file"
"swap-clean " "$RED * - Clean up the Swap Memory"
"texlive-up " "$RED * - Update the texlive packages"
"up-db " "$RED * - Update the database for the 'locate'"
"w " " - Menu with whiptail, where you can call the others options (the same result with 'w' or '')"
"weather " " - Show the weather forecast (you can pass the name of the city as parameter)"
"work-fbi " " - Write <zero>/<random> value in one ISO file to wipe trace of old deleted file")
if [ "$colorPrint" == '' ]; then # set useColor on again if the use not pass "noColor"
useColor
fi
case $optionInput in
"--help" | "-h" | "help" | 'h' )
help() {
echo -e "$CYAN# Show this help message (the same result with \"help\", \"--help\", \"-h\" or 'h') #$NC"
echo -e "\n$RED Obs$CYAN:$RED * root required,$BLUE = X server required$CYAN\nOptions:"
countOption=0
optionVectorSize=${#optionVector[*]}
while [ "$countOption" -lt "$optionVectorSize" ]; do
echo -e " $GREEN${optionVector[$countOption]}$CYAN${optionVector[$countOption+1]}"
countOption=$((countOption + 2))
done
}
help
;;
'' | 'w' )
whiptailMenu() {
echo -e "$CYAN# Menu with whiptail, where you can call the options above (the same result with 'w' or '') #$NC"
eval "$(resize)"
heightWhiptail=$((LINES - 5))
widthWhiptail=$((COLUMNS - 5))
if [ "$LINES" -lt 16 ]; then
echo -e "$RED\nTerminal with very small size. Use one terminal with at least 16 columns (actual size line: $LINES columns: $COLUMNS)$NC"
echo -e "$GREEN\nRunning: $0 $colorPrint notPrintHeader --help$CYAN\n" | sed 's/ / /g'
$0 "$colorPrint" notPrintHeader --help
else
heightMenuBoxWhiptail=$((LINES - 15))
#whiptail --title "<title of box menu>" --menu "<text to be show>" <height> <width> <height of box menu> \
#[ <tag> <item> ] [ <tag> <item> ] [ <tag> <item> ]
itemSelected=$(whiptail --title "#___ Script to usual commands ___#" --menu "Obs.: * root required, = X server required
Options:" $heightWhiptail $widthWhiptail $heightMenuBoxWhiptail \
"${optionVector[0]}" "${optionVector[1]}" \
"${optionVector[2]}" "${optionVector[3]}" \
"${optionVector[4]}" "${optionVector[5]}" \
"${optionVector[6]}" "${optionVector[7]}" \
"${optionVector[8]}" "${optionVector[9]}" \
"${optionVector[10]}" "${optionVector[11]}" \
"${optionVector[12]}" "${optionVector[13]}" \
"${optionVector[14]}" "${optionVector[15]}" \
"${optionVector[16]}" "${optionVector[17]}" \
"${optionVector[18]}" "${optionVector[19]}" \
"${optionVector[20]}" "${optionVector[21]}" \
"${optionVector[22]}" "${optionVector[23]}" \
"${optionVector[24]}" "${optionVector[25]}" \
"${optionVector[26]}" "${optionVector[27]}" \
"${optionVector[28]}" "${optionVector[29]}" \
"${optionVector[30]}" "${optionVector[31]}" \
"${optionVector[32]}" "${optionVector[33]}" \
"${optionVector[34]}" "${optionVector[35]}" \
"${optionVector[36]}" "${optionVector[37]}" \
"${optionVector[38]}" "${optionVector[39]}" \
"${optionVector[40]}" "${optionVector[41]}" \
"${optionVector[42]}" "${optionVector[43]}" \
"${optionVector[44]}" "${optionVector[45]}" \
"${optionVector[46]}" "${optionVector[47]}" \
"${optionVector[48]}" "${optionVector[49]}" \
"${optionVector[50]}" "${optionVector[51]}" \
"${optionVector[52]}" "${optionVector[53]}" \
"${optionVector[54]}" "${optionVector[55]}" \
"${optionVector[56]}" "${optionVector[57]}" \
"${optionVector[58]}" "${optionVector[59]}" \
"${optionVector[60]}" "${optionVector[61]}" \
"${optionVector[62]}" "${optionVector[63]}" \
"${optionVector[64]}" "${optionVector[65]}" \
"${optionVector[66]}" "${optionVector[67]}" \
"${optionVector[68]}" "${optionVector[69]}" \
"${optionVector[70]}" "${optionVector[71]}" \
"${optionVector[72]}" "${optionVector[73]}" \
"${optionVector[74]}" "${optionVector[75]}" \
"${optionVector[76]}" "${optionVector[77]}" \
"${optionVector[78]}" "${optionVector[79]}" \
"${optionVector[80]}" "${optionVector[81]}" \
"${optionVector[82]}" "${optionVector[83]}" \
"${optionVector[84]}" "${optionVector[85]}" 3>&1 1>&2 2>&3)
if [ "$itemSelected" != '' ]; then
itemSelected=${itemSelected// /} # Remove space in the end of selected item
echo -e "$GREEN\nRunning: $0 $colorPrint notPrintHeader $itemSelected ${*} $CYAN\n" | sed 's/ / /g'
if [ "${*}" != '' ]; then # Check if has more parameters
$0 "$colorPrint" notPrintHeader "$itemSelected" "${*}"
else
$0 "$colorPrint" notPrintHeader "$itemSelected"
fi
fi
fi
}
whiptailMenu "${*:2}"
;;
esac
;;
"check-pkg-i" )
echo -e "$CYAN# Check if all packages in a folder (and subfolders) are installed #$NC"
folderWork=$2
if [ "$folderWork" == '' ]; then
echo -e "$RED\nError: You need pass the folder to work"
elif [ ! -d "$folderWork" ]; then
echo -e "$RED\nError: The folder \"$folderWork\" not exist"
else
echo -e "\n$CYAN Folder to work with: $folderWork$NC"
files=$(find "$folderWork" -type f | grep -E "txz$|tgz$")
filesName=$(echo "$files" | rev | cut -d '.' -f2- | cut -d '/' -f1 | rev)
echo -e "$CYAN\nPackages not installed:$NC"
linePkg=1
pkgInstalled=''
pkgNotInstalled=''
for pkg in $filesName; do
locatePkg=$(ls "/var/log/packages/$pkg" 2> /dev/null)
if [ "$locatePkg" == '' ]; then
pkgNotInstalled=$pkgNotInstalled$(echo "$files" | sed -n ${linePkg}p)"\n"
else
pkgInstalled=$pkgInstalled$(echo "$files" | sed -n ${linePkg}p)"\n"
fi
((linePkg++))
done
echo -e "$pkgNotInstalled" | sort
echo -en "$CYAN\nPrint the packages installed? (y)es or (n)o: $NC"
read -r printPkg
if [ "$printPkg" == 'y' ]; then
echo -e "$pkgInstalled" | sort
fi
fi
;;
"git-gc" )
echo -e "$CYAN# Run git gc (|--auto|--aggressive) in the subfolders #$NC"
echo -e "\nCommands available:"
echo "1 - \"git gc\"" # Cleanup unnecessary files and optimize the local repository
echo "2 - \"git gc --auto\"" # Checks whether any housekeeping is required; if not, it exits without performing any work
echo "3 - \"git gc --aggressive\"" # More aggressively, optimize the repository at the expense of taking much more time
echo -n "Which option you want? (hit enter to insert 1): "
read -r git_option
git_command="git gc"
if [ "$git_option" == 2 ]; then
git_command="$git_command --auto"
elif [ "$git_option" == 3 ]; then
git_command="$git_command --aggressive"
fi
for folder in $(find . -maxdepth 1 -type d | grep -v "^.$"| sort); do
echo -e "\n$BLUE Folder: $GREEN$folder/$NC"
cd "$folder/" || exit
if [ -d ".git/" ]; then
echo -e "$BLUE Running: $GREEN$git_command$NC\n"
$git_command
else
echo -e "$RED Not a git folder$NC"
fi
cd ../ || exit
done
;;
"git-up")
echo -e "$CYAN# Run git pull and force update to the local files (deleting changes) with the remote in the subfolders #$NC"
IFS=$(echo -en "\n\b") # Change the Internal Field Separator (IFS) to "\n\b"
for folder in $(find . -maxdepth 1 -type d | grep -v "^.$"| sort); do
echo -e "\n$BLUE Folder: $GREEN$folder/$NC"
cd "$folder/" || exit
if [ -d ".git/" ]; then
if ! git pull; then # $? != 0
echo -en "\n$CYAN Local files with changes. Force the update? (y)es or n(o):$NC "
read -r force_up
if [ "$force_up" == "y" ]; then
git fetch --all # Fetch all changes
git reset --hard origin/master # Reset the master
git pull # Pull/update
else
echo -e "$RED Repository not updated$NC"
fi
fi
else
echo -e "$RED Not a git folder$NC"
fi
cd ../ || exit
done
;;
"file-equal" )
echo -e "$CYAN# Look for equal files using md5sum in the current folder (and subfolders) #$NC"
IFS=$(echo -en "\n\b") # Change the Internal Field Separator (IFS) to "\n\b"
fileType=$2
if [ "$fileType" == '' ]; then
echo -e "$CYAN\nWant check all files or just a type of files?$NC"
echo -en "${CYAN}Hit enter to all files or the type (e.g. txt or pdf):$NC "
read -r fileType
fi
echo -e "$BLUE\n Tip: use the option \"auto\" to automatic run the code (use default options)$NC"
autoOnOff=$3
echo -e "$CYAN\nWant check the files recursively (this folder and all his subfolders) or only this folder?$NC"
echo -en "${CYAN}1 to recursively - 2 to only this folder (hit enter to all folders):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r allFolderOrNot
else
allFolderOrNot=1
fi
if [ "$allFolderOrNot" == 2 ]; then
recursiveFolderValue="-maxdepth 1" # Set the max deep to 1, or just this folder
else
recursiveFolderValue=''
fi
echo -en "$GREEN\nRunning md5sum, can take a while. Please wait, checking "
if [ "$fileType" == '' ]; then
echo -en "all files...$NC"
fileAndMd5=$(eval find . "$recursiveFolderValue" -type f -print0 | xargs -0 md5sum) # Get md5sum of the files
else
echo -en "the files with \"$fileType\" in the name...$NC"
fileAndMd5Tmp=$(eval find . "$recursiveFolderValue" -type f | grep "$fileType")
if [ "$fileAndMd5Tmp" == '' ]; then
echo -e "\n\n${RED}Error: not found any file with \"$fileType\"!$NC\n"
exit 1
fi
for file in $fileAndMd5Tmp; do
fileAndMd5=$fileAndMd5"\n"$(md5sum "$file")
done
fileAndMd5=$(echo -e "$fileAndMd5") # "Create" the new lines
fi
fileAndMd5=$(echo -e "$fileAndMd5" | sed 's/.\///1') # Remove ./ from begin of files names
fileAndMd5=$(echo "$fileAndMd5" | sort) # Sort by the md5sum
md5Files=$(echo "$fileAndMd5" | cut -d " " -f1) # Get only the md5sum
for value in $md5Files; do
if [ "$valueBack" == "$value" ]; then # Look for all values that are equal
equalFiles="$equalFiles$value|"
fi
valueBack=$value
done
equalFiles=${equalFiles::-1} # Remove the last | (the last character)
if [ "$equalFiles" == '' ]; then
echo -e "$GREEN\n\n### All files are different by md5sum! ###$NC"
else
echo -en "$BLUE\n\n### These file(s) are equal:$NC"
filesEqual=$(echo "$fileAndMd5" | grep -E "$equalFiles") # Grep all files equal
valueBack='' # Clean the value in valueBack
for value in $filesEqual; do
valueNow=$(echo "$value" | cut -d " " -f1)
if [ "$valueNow" != "$valueBack" ]; then
echo # Add a new line between file different in the print on the terminal
else
fileTmp=$(echo "$value" | cut -d "/" -f2-)
FilesToWork=$FilesToWork$(echo -e "\n$fileTmp")
fi
valueBack=$valueNow
echo "$value"
done
filesDifferent=$(echo "$fileAndMd5" | grep -vE "$equalFiles") # Grep all files different
if [ "$filesDifferent" != '' ]; then
echo -e "$CYAN\nWant to print the file(s) that are different?$NC"
echo -en "$CYAN(y)es - (n)o (hit enter to yes):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r printDifferent
else
printDifferent='y'
fi
if [ "$printDifferent" != 'n' ]; then
echo -e "$BLUE\n### These file(s) are different:$NC"
echo "$filesDifferent" | sort -k 2
fi
else
echo -e "$BLUE\n### There is no unique file(s)! ###$NC"
fi
tmpFolder="equal_files_"$RANDOM
echo -en "\n$RED### Files to be moved:$GREEN"
echo "$FilesToWork" | sort -k 2
echo -e "$RED\nWant to move (leave one) the equal file(s) to a TMP folder $GREEN($tmpFolder)?"
echo -en "$RED(y)es - (n)o (hit enter to no):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r moveEqual
else
moveEqual='y'
fi
if [ "$moveEqual" == 'y' ]; then
mkdir "$tmpFolder" 2> /dev/null
FilesToWork_Name=$(echo "$FilesToWork" | cut -d ' ' -f3) # Only file name
for value in $FilesToWork_Name; do
createFolder=$(echo "$value" | grep "/")
if [ "$createFolder" != '' ]; then
folderToCreate=$(echo "$value" | rev | cut -d "/" -f2- | rev)
folderToCreate=$tmpFolder"/"$folderToCreate
mkdir -p "$folderToCreate" 2> /dev/null
else
folderToCreate=$tmpFolder
fi
mv "$value" "$folderToCreate"
done
echo -e "$BLUE\n\tFiles moved to: $GREEN$PWD/$tmpFolder/$NC"
else
echo -e "$BLUE\n\tFiles not moved!"
fi
fi
;;
"folder-equal" )
echo -e "$CYAN# Look for equal files in \"folder2\" that are in \"folder1\" using md5sum #$NC"
IFS=$(echo -en "\n\b") # Change the Internal Field Separator (IFS) to "\n\b"
folder1=$2
folder2=$3
echo -e "\n${BLUE}folder1: $GREEN\"$folder1\"$NC\n${BLUE}folder2: $GREEN\"$folder2\"$NC"
if [ "$folder1" == '' ] || [ "$folder2" == '' ]; then
echo -e "$RED\nError: You need pass the folders to work: you pass: \"$folder1\" and \"$folder2\"$NC"
elif [ ! -d "$folder1" ] || [ ! -d "$folder2" ]; then
echo -e "$RED\nError: The folder \"$folder1\" or \"$folder2\" not exist$NC"
else
folder1=${folder1// /\\ } # Change the empty spaces " " in the name to "\ "
folder2=${folder2// /\\ }
fileType=$4
if [ "$fileType" == '' ]; then
echo -e "$CYAN\nWant check all files or just a type of files?$NC"
echo -en "${CYAN}Hit enter to all files or the type (e.g., txt or pdf):$NC "
read -r fileType
fi
echo -e "$BLUE\n Tip: use the option \"auto\" to automatic run the code (use default options)$NC"
if [ "$fileType" == "auto" ]; then # If there is no file type, but has parameter "auto"
autoOnOff=$4
else
autoOnOff=$5
fi
echo -e "$CYAN\nWant check the files recursively (this source folders and all subfolders) or only in the source folders?$NC"
echo -en "${CYAN}1 to recursively - 2 to only in source folder (hit enter to all folders):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r allFolderOrNot
else
allFolderOrNot=1
fi
if [ "$allFolderOrNot" == 2 ]; then
recursiveFolderValue="-maxdepth 1" # Set the max deep to 1, or just this folder
else
recursiveFolderValue=''
fi
echo -en "$GREEN\nRunning md5sum, can take a while. Please wait, checking "
if [ "$fileType" == '' ]; then
echo -en "${BLUE}all files...$NC"
fileAndMd5F1=$(eval find "$folder1" "$recursiveFolderValue" -type f -print0 | xargs -0 md5sum) # Get md5sum of the files
fileAndMd5F2=$(eval find "$folder2" "$recursiveFolderValue" -type f -print0 | xargs -0 md5sum) # Get md5sum of the files
else
echo -en "${BLUE}the files with $GREEN\"$fileType\"$BLUE in the name...$NC"
fileAndMd5TmpF1=$(eval find "$folder1" "$recursiveFolderValue" -type f | grep "$fileType")
fileAndMd5TmpF2=$(eval find "$folder2" "$recursiveFolderValue" -type f | grep "$fileType")
for file in $fileAndMd5TmpF1; do
fileAndMd5F1=$fileAndMd5F1"\n"$(md5sum "$file")
done
for file in $fileAndMd5TmpF2; do
fileAndMd5F2=$fileAndMd5F2"\n"$(md5sum "$file")
done
fileAndMd5F1=$(echo -e "$fileAndMd5F1") # "Create" the new lines
fileAndMd5F2=$(echo -e "$fileAndMd5F2")
fi
fileAndMd5F1=$(echo "$fileAndMd5F1" | sort) # Sort by the md5sum
fileAndMd5F2=$(echo "$fileAndMd5F2" | sort) # Sort by the md5sum
fileAndMd5FAll=$(echo -e "$fileAndMd5F1\n$fileAndMd5F2" | sort)
md5FilesF1=$(echo "$fileAndMd5F1" | cut -d " " -f1) # Get only de md5sum
md5FilesF2=$(echo "$fileAndMd5F2" | cut -d " " -f1) # Get only de md5sum
for valueF1 in $md5FilesF1; do
for valueF2 in $md5FilesF2; do
if [ "$valueF1" == "$valueF2" ]; then # Look for all values equal
equalFiles="$equalFiles$valueF2|"
fi
done
done
equalFiles=${equalFiles::-1} # Remove the last | (the last character)
if [ "$equalFiles" == '' ]; then
echo -e "$GREEN\n\n### All files are different by md5sum ###$NC\n"
else
echo -en "$BLUE\n\n### These file(s) in $GREEN\"$folder2\"$BLUE are equal in $GREEN\"$folder1\"$BLUE:$NC"
filesEqual=$(echo "$fileAndMd5FAll" | grep -E "$equalFiles") # Grep all files equal
valueBack='' # Clean the value in valueBack
for value in $filesEqual; do
valueNow=$(echo "$value" | cut -d " " -f1)
if [ "$valueNow" != "$valueBack" ]; then
echo # Add a new line between file different in the print on the terminal
fi
valueBack=$valueNow
echo "$value"
done
filesEqual=$(echo "$fileAndMd5F2" | grep -E "$equalFiles") # Grep all files equal
echo -e "$BLUE\n### File(s) equal summary (only the equal file(s) in $GREEN\"$folder2\"$BLUE):$NC\n$filesEqual"
for value in $filesEqual; do
fileTmp=$(echo "$value" | cut -d " " -f3-) # Cut the second space from md5sum to end
FilesToWork=$FilesToWork$(echo -e "\n$fileTmp")
done
filesDifferent=$(echo -e "$fileAndMd5F1\n$fileAndMd5F2" | grep -vE "$equalFiles") # Grep all files different
if [ "$filesDifferent" != '' ]; then
echo -e "$CYAN\nWant to print the file(s) that are different?$NC"
echo -en "$CYAN(y)es - (n)o (hit enter to yes):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r printDifferent
else
printDifferent='y'
fi
if [ "$printDifferent" != 'n' ]; then
echo -e "$BLUE\n### These file(s) are different:$NC"
echo "$filesDifferent" | sort -k 2
fi
else
echo -e "$BLUE\n### There is no unique file(s) ###$NC"
fi
tmpFolder="equal_files_"$RANDOM
echo -en "\n$RED### Files to be moved:$GREEN"
echo "$FilesToWork" | sort -k 2
echo -e "$RED\nWant to move (leave one) the equal file(s) to a TMP folder $GREEN($tmpFolder)?"
echo -en "$RED(y)es - (n)o (hit enter to no):$NC "
if [ "$autoOnOff" != "auto" ]; then
read -r moveEqual
else
moveEqual='y'
fi
if [ "$moveEqual" == 'y' ]; then
mkdir "$tmpFolder" 2> /dev/null
for value in $FilesToWork; do
createFolder=$(echo "$value" | grep "/")
if [ "$createFolder" != '' ]; then
folderToCreate=$(echo "$value" | rev | cut -d "/" -f2- | rev)
folderToCreate=$tmpFolder"/"$folderToCreate
mkdir -p "$folderToCreate" 2> /dev/null
else
folderToCreate=$tmpFolder
fi
mv "$value" "$folderToCreate"
done
echo -e "$BLUE\n\tFiles moved to: $GREEN$PWD/$tmpFolder/$NC"
else
echo -e "$BLUE\n\tFiles not moved!"
fi
fi
fi
;;
"kill" )
echo -e "$CYAN# Search for program with pattern/name and (can) kill it #$NC"
program_name=$2
if [ "$program_name" == '' ]; then
echo -en "\nInsert the program name: "
read -r program_name
fi
list_process=$(ps aux | grep -i "$program_name" | grep -vE "grep|$0")
if [ "$list_process" != '' ]; then
echo -e "\n$BLUE List of process:$NC"
echo "USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"
echo "$list_process"
PID=$(echo "$list_process" | awk '{print $2}')
echo -e "\n$BLUE PID(s):\n$NC$PID"
for process in $PID; do
echo -e "\n$CYAN PID: $RED$process$NC"
echo "USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"
echo -e "$list_process" | grep " $process "
echo -en "$RED\nKill this process?\n(y)es - (n)o (hit enter to no or t no end function):$NC "
read -r kill_process
if [ "$kill_process" == 'y' ]; then
echo " + kill -9 $process"
kill -9 "$process"
elif [ "$kill_process" == 't' ]; then
break
fi
done
else
echo -e "$RED\nError: Not found any process with \"$program_name\""
fi
;;
"sub-extract" ) # Need ffmpeg
echo -e "$CYAN# Extract subtitle from a video file #$NC"
fileName=$2
if [ "$fileName" != '' ]; then
subtitleInfoGeneral=$(ffmpeg -i "$fileName" 2>&1 | grep "Stream.*Subtitle") # Grep information about subtitles in the file
subtitleNumber=$(echo -e "$subtitleInfoGeneral" | cut -d":" -f2 | cut -d "(" -f1 | sed ':a;N;$!ba;s/\n/ /g') # Grep subtitles numbers
subtitleInfo=$(echo "$subtitleInfoGeneral" | cut -d":" -f2 | tr "(" " " | cut -d ")" -f1) # Grep subtitles number and language
if [ "$subtitleNumber" == '' ]; then # Empty if not found any subtitle in the file
echo -e "$RED\nError: Not found any subtitle in the file: $GREEN\"$fileName\""
else
echo -e "$CYAN\nSubtitles available in the file $GREEN\"$fileName\"$CYAN:$GREEN\n$subtitleInfo"
echo -en "$CYAN\nWhich one you want? (only valid numbers: $GREEN$subtitleNumber$CYAN): $NC"
read -r subNumber
if echo "$subNumber" | grep -q "[[:digit:]]"; then # Test if was insert only number
lastPart=$(echo "$subtitleInfo" | grep "^$subNumber ") # Grep the info (number language) about the subtitle wanted, if exists
if [ "$lastPart" != '' ]; then
echo -e "\nExtracting the subtitle \"$lastPart\" from the file \"$fileName\""
fileNameTmp=$(echo "$fileName" | rev | cut -d "." -f2- | rev)
echo -e "That will be save as \"$fileNameTmp-$lastPart.srt\"\n"
echo -e "${GREEN}Running:\nffmpeg -i \"$fileName\" -an -vn -map 0:$subNumber -c:s:0 srt \"${fileNameTmp}-${lastPart}.srt\"\n$NC"
ffmpeg -i "$fileName" -an -vn -map 0:"$subNumber" -c:s:0 srt "${fileNameTmp}-${lastPart}.srt"
echo -e "$CYAN\nSubtitle $GREEN\"$lastPart\"$CYAN from $GREEN\"$fileName\"$CYAN saved as $GREEN\"${fileNameTmp}-${lastPart}.srt\"$NC"
else
echo -e "$RED\nError: Not found the subtitle $GREEN\"$subNumber\"$RED in the file: $GREEN\"$fileName\"\n$CYAN one of: $GREEN$subtitleNumber$NC"
fi
else
echo -e "$RED\nError: The subtitle number must be a number$NC"
fi
fi
else
echo -e "$RED\nError: Need pass the file name$NC"
fi
;;
"audio-extract" ) # Need ffmpeg
echo -e "$CYAN# Extract audio from a video file #$NC"
fileName=$2
if [ "$fileName" != '' ]; then
audioInfoGeneral=$(ffmpeg -i "$fileName" 2>&1 | grep "Stream.*Audio") # Grep information about audio in the file
audioNumber=$(echo -e "$audioInfoGeneral" | cut -d":" -f2 | cut -d "(" -f1 | sed ':a;N;$!ba;s/\n/ /g') # Grep audio numbers
audioInfo=$(echo "$audioInfoGeneral" | cut -d":" -f2 | tr "(" " " | cut -d ")" -f1) # Grep audio number and language
if [ "$audioNumber" == '' ]; then # Empty if not found any audio in the file
echo -e "$RED\nError: Not found any audio in the file: $GREEN\"$fileName\""
else
echo -e "$CYAN\nAudio available in the file $GREEN\"$fileName\"$CYAN:$GREEN\n$audioInfo"
echo -en "$CYAN\nWhich one you want? (only valid numbers: $GREEN$audioNumber$CYAN): $NC"
read -r audioNumber
if echo "$audioNumber" | grep -q "[[:digit:]]"; then # Test if was insert only number
((audioNumber-=1)) # Remove 1, audio start in zero 0
lastPart=$(echo "0 $audioInfo" | grep "^$audioNumber ") # Grep the info (number language) about the audio wanted, if exists
if [ "$lastPart" != '' ]; then
echo -e "\nExtracting the audio \"$lastPart\" from the file \"$fileName\""
fileNameTmp=$(echo "$fileName" | rev | cut -d "." -f2- | rev)
echo -e "That will be save as \"$fileNameTmp-$lastPart.mp3\"\n"
echo -e "${GREEN}Running:\nffmpeg -i \"$fileName\" -map 0:a:$audioNumber \"${fileNameTmp}-${lastPart}.mp3\"\n$NC"
ffmpeg -i "$fileName" -map 0:a:"$audioNumber" "${fileNameTmp}-${lastPart}.mp3"
echo -e "$CYAN\nAudio $GREEN\"$lastPart\"$CYAN from $GREEN\"$fileName\"$CYAN saved as $GREEN\"${fileNameTmp}-${lastPart}.mp3\"$NC"
else
echo -e "$RED\nError: Not found the audio $GREEN\"$audioNumber\"$RED in the file: $GREEN\"$fileName\"\n$CYAN one of: $GREEN$audioNumber$NC"
fi
else
echo -e "$RED\nError: The audio number must be a number$NC"
fi
fi
else
echo -e "$RED\nError: Need pass the file name$NC"
fi
;;
"mem-use" )
echo -e "$CYAN# Get the all (shared and specific) use of memory RAM from one process/pattern #$NC"
if [ "$2" == '' ]; then
echo -en "\nInsert the pattern (process name) to search: "
read -r process_pattern
else
process_pattern=$2
fi
if [ "$process_pattern" != '' ]; then
process_list=$(ps aux)
process_pattern_list=$(echo "$process_list" | grep -E "USER|$process_pattern" | grep -v -E "$0|grep")
mem_percentage=$(echo "$process_pattern_list" | grep -v "USER" | awk '{print $4}')
if [ "$mem_percentage" == '' ]; then
echo -e "$RED\nError: Not found any process with the pattern $BLUE\"$process_pattern\"$RED. Try with another."
else
mem_percentage_sum=0
for mem_now in $mem_percentage; do
mem_percentage_sum=$(echo "scale=2; $mem_percentage_sum+$mem_now" | bc)
done
total_mem=$(free -m | head -n 2 | tail -n 1 | awk '{print $2}')
use_mem=$(echo "($total_mem*$mem_percentage_sum)/100" | bc)
if [ "$(echo "$mem_percentage_sum < 1" | bc -l)" == 1 ]; then
mem_percentage_sum="0$mem_percentage_sum"
fi
echo -en "\nThe process $BLUE\"$process_pattern\"$NC is using: $RED$use_mem$NC MiB"
echo -e " or $RED$mem_percentage_sum$NC % of $GREEN$total_mem MiB$NC\n"
echo -e "$process_pattern_list\n"
fi
else
echo -e "$RED\nError: You need insert some pattern/process name to search, e.g., $0 mem-use opera$NC"
fi
;;
"s-pkg-f" )
echo -e "$CYAN# Search in the installed package folder (/var/log/packages/) for one pattern (-f of fast) #$NC"
if [ "$2" == '' ]; then
echo -en "$CYAN\nPackage file or pattern to search:$NC "
read -r filePackage
else
filePackage=$2
fi
echo -en "$CYAN\nSearching, please wait...$NC\n"
grep -rn "$filePackage" /var/log/packages/* --color=auto
;;
"s-pkg-s" )
echo -e "$CYAN# Search in the installed package folder (/var/log/packages/) for one pattern (-r of summary files) #$NC"
if [ "$2" == '' ]; then
echo -en "$CYAN\nPackage file or pattern to search:$NC "
read -r filePackage
else
filePackage=$2
fi
echo -en "$CYAN\nSearching, please wait...$NC"
tmpFileName=$(mktemp) # Create a tmp file
tmpFileFull=$(mktemp)
for fileInTheFolder in /var/log/packages/*; do
if grep -q "$filePackage" < "$fileInTheFolder"; then # Grep the "filePackage" from the file in /var/log/packages
grep "PACKAGE NAME" < "$fileInTheFolder" >> "$tmpFileName" # Grep the package name from the has the "filePackage"
cat "$fileInTheFolder" >> "$tmpFileFull" # Print all info about the package
echo >> "$tmpFileFull" # Insert one new line
fi
done
sizeResultFile=$(du "$tmpFileName" | cut -f1)
if [ "$sizeResultFile" != 0 ]; then
echo -e "\n\nResults saved in \"$tmpFileName\" and \"$tmpFileFull\" tmp files\n"
echo -en "Open this files with kwrite or print them in the terminal?\n(k)write - (t)erminal: "
read -r openProgram
if [ "$openProgram" == 'k' ]; then
kwrite "$tmpFileName"
kwrite "$tmpFileFull"
else
echo -e "\nPackage(s) with '$filePackage':\n"
cat "$tmpFileName"
echo -en "\nPrint this package(s) in terminal?\n(y)es - (p)artial, only the matches - (n)o: "
read -r continuePrint
echo
if [ "$continuePrint" == 'y' ]; then
cat "$tmpFileFull"
elif [ "$continuePrint" == 'p' ]; then
grep "$filePackage" < "$tmpFileFull"
fi
fi
else
echo -e "\n\n No result was found"
fi
echo -e "\nDeleting the log files used in this script\n"
rm "$tmpFileName" "$tmpFileFull"
;;
"work-fbi" )
echo -e "$CYAN# Write <zero>/<random> value in one ISO file to wipe trace of old deleted file #$NC"
echo -e "\nWarning: Depending on how big is the amount of free space, this can take a long time"
freeSpace=$(df . | awk '/[0-9]%/{print $(NF-2)}') # Free space local/pwd folder
freeSpaceMiB=$(echo "scale=2; $freeSpace/1024" | bc) # Free space in MiB
freeSpaceGiB=$(echo "scale=2; $freeSpace/(1024*1024)" | bc) # Free space in GiB
timeAvgMin=$(echo "($freeSpaceMiB/30)/60" | bc)
echo -e "\nThere are$GREEN $freeSpaceGiB$CYAN GiB$NC ($GREEN$freeSpaceMiB$CYAN MiB$NC) free in this folder/disk/partition (that will be write)"
echo -e "Considering$CYAN 30 MiB/s$NC in speed of write, will take$GREEN $timeAvgMin min$NC to finish this job"
echo -en "\nWant continue? (y)es - (n)o: "
read -r continueDd
if [ "$continueDd" == 'y' ]; then
fileName="work-fbi_" # Create a ISO file with a random part name
fileName+=$(date +%s | md5sum | head -c 10)
fileName+=".iso"
echo "You can use <zero> or <random> value"
echo "Using <random> value is better to overwrite your deleted file"
echo "Otherwise, is slower (almost 10 times) then use <zero> value"
echo "Long story short, use <zero> if you has not deleted pretty good sensitive data"
echo -en "\nUse random or zero value?\n(r)andom - (z)ero: "
read -r continueRandomOrZero
startAtSeconds=$(date +%s)
if [ "$continueRandomOrZero" == 'r' ]; then
typeWriteDd="random"
else
typeWriteDd="zero"
fi
echo -en "\nWriting <$typeWriteDd> value in the \"$fileName\" tmp file. Please wait...\n\n"
if [ "$continueRandomOrZero" == 'r' ]; then
dd if=/dev/urandom of="$fileName" iflag=nocache oflag=direct bs=1M conv=notrunc status=progress # Write <random> value to wipe the data
else
dd if=/dev/zero of="$fileName" iflag=nocache oflag=direct bs=1M conv=notrunc status=progress # Write <zero> value to wipe the data
fi
endsAtSeconds=$(date +%s)
timeTakeMin=$(echo "scale=2; ($endsAtSeconds - $startAtSeconds)/60" | bc)
echo -e "\nFinished to write the file - this take $timeTakeMin min"
rm "$fileName" # Delete the <big> file generated
echo -e "\nThe \"$fileName\" tmp file was deleted and the end of the job"
fi
;;
"ip" )
echo -e "$CYAN# Get your IP #$NC"
localIP=$(/sbin/ifconfig | grep broadcast | awk '{print $2}')
echo -e "$CYAN\nLocal IP:$GREEN $localIP$CYAN"
externalIP=$(wget -qO - icanhazip.com)
echo -e "External IP:$GREEN $externalIP$NC"
;;
"cpu-max" )
echo -e "$CYAN# Show the 10 process with more CPU use #$NC\n"
ps axo pid,%cpu,%mem,cmd --sort=-pcpu | head -n 11 | cut -d "-" -f1
;;
"mem-max" )
echo -e "$CYAN# Show the 10 process with more memory RAM use #$NC\n"
ps axo pid,%cpu,%mem,rss,cmd --sort -rss | head -n 11 | cut -d "-" -f1 | \
awk '{
for (x=1; x<=NF; x++) {
if (x == 1) {
printf("%-8s ", $x)
}else if (x == 2 || x == 3) {
printf("%-6s ", $x)
}else if (x == 4) {
if ($x == "RSS") {
printf("%8s ", $x)
} else {
printf("%8.2f MiB ", $x/1024)
}
} else {
printf("%-8s ", $x)
}
}
print("")
}'
;;
"day-s-i" )
echo -e "$CYAN# The day the system was installed #$NC"
dayInstall() {
# tune2fs -l /dev/sda1 or dumpe2fs /dev/sda1
partitionRoot=$(mount | grep "on / t" | cut -d ' ' -f1)
dayCreated=$(dumpe2fs "$partitionRoot" 2> /dev/null | grep "Filesystem created" | cut -d ' ' -f9-)
echo -e "$CYAN\nThe system was installed in:$GREEN $dayCreated$NC"
echo -e "Obs.: In some of the cases is just the day partition was created"
}
export -f dayInstall
export CYAN NC GREEN RED
su root -c 'dayInstall'
;;