-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathstandard_functions
1980 lines (1675 loc) · 50 KB
/
standard_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
#!/bin/bash
# _ _ _
# ___| |_ __ _ _ __ __| | __ _ _ __ __| |
# / __| __/ _` | '_ \ / _` |/ _` | '__/ _` |
# \__ \ || (_| | | | | (_| | (_| | | | (_| |
# |___/\__\__,_|_| |_|\__,_|\__,_|_| \__,_|
#
# __ _ _
# / _|_ _ _ __ ___| |_(_) ___ _ __ ___
# | |_| | | | '_ \ / __| __| |/ _ \| '_ \/ __|
# | _| |_| | | | | (__| |_| | (_) | | | \__ \
# |_| \__,_|_| |_|\___|\__|_|\___/|_| |_|___/
#
# All functions have long and descriptive names that start with
# two underscores (so they don't pollute the shells namespace).
# This functions are then "aliased" with shorter name (or
# names), that are specified in `~/.standardrc` configuration
# file. Be careful when changing long function names, because
# they might be used by other functions. Utility functions that
# are not meant to be aliased start with three underscores. Any
# new function that starts with two underscores will
# automatically be included in rc file when new shell is run.
########
# LESS #
########
# Runs less with:
# * ignore case when searching,
# * do not ring a bell,
# * do not mark empty lines with ~,
# * format prompt as "<page-number>/<all-pages> <filename>" and
# * set tabs to 4 spaces.
__displayTextOrFileInPager() {
less "${_LESS_OPTIONS[@]}" "$@"
}
# Prints with cat or displays with less contents of specified file,
# depending on the length of file. If it runs less then it starts
# diplaying text from the end if second argument is 'true'.
___printOrDisplayFileInPagerWithOrWithoutStartingAtEnd() {
noOfLines=$(cat "$2" 2>/dev/null \
| fold -w"$COLUMNS" \
| wc -l)
if [[ "$LINES" -gt "$noOfLines" ]]; then
cat "$2"
else
if [[ "$1" == 'true' ]]; then
__displayTextOrFileInPager +G "$2" 2>/dev/null
else
__displayTextOrFileInPager "$2" 2>/dev/null
fi
fi
}
# Prints with cat or displays with less piped text, depending on
# the length of input. If it runs less then it starts diplaying text
# from end if first argument is 'true'.
___printOrDisplayTextInPagerWithOrWithoutStartingAtEnd() {
input=$(cat)
noOfLines=$(echo "$input" | fold -w"$COLUMNS" | wc -l)
if [[ "$LINES" -gt "$noOfLines" ]]; then
echo "$input" #| cat
# Maybe cat is necessary in some cases because of
# colors, I forgot if there is a reason for cat to
# be here.
else
if [[ "$1" == 'true' ]]; then
echo "$input" | __displayTextOrFileInPager +G 2>/dev/null
else
echo "$input" | __displayTextOrFileInPager 2>/dev/null
fi
fi
}
# If any arguments are passed, then assumes the input is a file, whose
# name is specified by the argument. If there are no arguments, it then
# assumes the input is streamed in with a pipe.
___printOrDisplayTextOrFileInPagerWithOrWithoutStartingAtEnd() {
if [[ "$#" -gt 1 ]]; then
___printOrDisplayFileInPagerWithOrWithoutStartingAtEnd "$@"
else
cat | ___printOrDisplayTextInPagerWithOrWithoutStartingAtEnd "$@"
fi
}
# Runs cat or less, depending on number of lines in file or
# input.
__printOrDisplayTextOrFileInPager() {
___printOrDisplayTextOrFileInPagerWithOrWithoutStartingAtEnd 'false' "$@"
}
# Open cat or less +G (starts at the end of file), depending on
# no of lines of file or input.
___printOrDisplayTextOrFileInPagerStartingAtEnd() {
___printOrDisplayTextOrFileInPagerWithOrWithoutStartingAtEnd 'true' "$@"
}
# If file specified then runs cat or less, depending on no of
# lines of file. If input is piped, then it prints line by
# line. If all screen is filled, then it runs less.
___printTextOrFileUntilPageIsFilledThenDisplayInPager() {
if [[ "$#" -gt 0 ]]; then
___printOrDisplayFileInPagerWithOrWithoutStartingAtEnd 'false' "$1"
else
noOfLines=0
input=""
while read -r line; do
input+=("$line")
realLines=$(echo "$line" | fold -w"$COLUMNS" | wc -l)
let noOfLines="$noOfLines"+"$realLines"
if [ $noOfLines -gt $LINES ]; then
(for inputLine in "${input[@]}"; do
echo "$inputLine"
done
while read -r line; do
echo "$line"
done) | less 2>/dev/null
exit
fi
echo "$line"
done
fi
}
######
# LS #
######
# All other ls functions end up calling this one. It runs ls with:
# * append indicator,
# * sort alphabetically by extension,
# * list by columns,
# * use color when stdout is connected to terminal and
# * group directories before files.
___listDirectoryContents() {
ls "${_LS_OPTIONS[@]}" "$@"
}
# Calls ___listDirectoryContents with:
# * set width to screen width or 69, whichever is smaller.
___listDirectoryContentsUsingShortListingFormat() {
width=$(
widthLimit=69
if [[ "$COLUMNS" -lt "$widthLimit" ]]; then
echo "$COLUMNS"
else
echo "$widthLimit"
fi)
___listDirectoryContents --width="$width" "$@"
}
# Calls ___listDirectoryContents with:
# * use long listing format,
# * do not print groups,
# * do not list owner,
# * print sizes in human readable format and
# * print date as: '<month-by-word>, <day-of-month>, <year>,
# <hour>:<minute>'.
___listDirectoryContentsUsingMediumListingFormat() {
___listDirectoryContents "${_LS_MEDIUM_OPTIONS[@]}" "$@"
}
# Calls ___listDirectoryContents with:
# * use long listing format.
___listDirectoryContentsUsingLongListingFormat() {
___listDirectoryContents -l "$@"
}
# $1 - function that lists dir contents
# ... - rest of parameters
___displayOutputOfListingFunctionInPagerIfItDoesentFitScreen() {
listingFunction="$1"
shift
functionOutput=$("$listingFunction" --color=always "$@")
if [[ $? -ne 0 ]]; then
return
fi
noOfLines=$(
echo "$functionOutput" \
| fold -w"$COLUMNS" \
| wc -l)
if [[ "$LINES" -gt "$noOfLines" ]]; then
echo "$functionOutput"
else
echo "$functionOutput" | __displayTextOrFileInPager +G
fi
}
__listOrDisplayDirectoryContentsInPagerUsingShortListingFormat() {
___displayOutputOfListingFunctionInPagerIfItDoesentFitScreen \
___listDirectoryContentsUsingShortListingFormat "$@"
}
__listOrDisplayDirectoryContentsInPagerUsingMediumListingFormat() {
___displayOutputOfListingFunctionInPagerIfItDoesentFitScreen \
___listDirectoryContentsUsingMediumListingFormat "$@"
}
__listOrDisplayDirectoryContentsInPagerUsingLongListingFormat() {
___displayOutputOfListingFunctionInPagerIfItDoesentFitScreen \
___listDirectoryContentsUsingLongListingFormat "$@"
}
__listOrDisplayAllDirectoryContentsInPagerUsingShortListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingShortListingFormat \
--almost-all "$@"
}
__listOrDisplayAllDirectoryContentsInPagerUsingMediumListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingMediumListingFormat \
--almost-all "$@"
}
__listOrDisplayAllDirectoryContentsInPagerUsingLongListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingLongListingFormat \
--almost-all "$@"
}
__listOrDisplayDirectoryContentsInPagerOrderedByDateUsingShortListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingShortListingFormat \
-t "$@"
}
__listOrDisplayDirectoryContentsInPagerOrderedByDateUsingMediumListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingMediumListingFormat \
-t "$@"
}
__listOrDisplayDirectoryContentsInPagerOrderedByDateUsingLongListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingLongListingFormat \
-t "$@"
}
__listOrDisplayMatchingDirectoriesInPagerUsingShortListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingShortListingFormat \
--directory "$@"
}
__listOrDisplayMatchingDirectoriesInPagerUsingMediumListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingMediumListingFormat \
--directory "$@"
}
__listOrDisplayMatchingDirectoriesInPagerUsingLongListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingLongListingFormat \
--directory "$@"
}
__listOrDisplayInPagerOneDirectoryItemPerLineUsingShortListingFormat() {
__listOrDisplayDirectoryContentsInPagerUsingShortListingFormat \
-1 "$@"
}
__listOrDisplayInPagerOneDirectoryItemPerLineIncludingHiddenFilesUsingShortListingFormat() {
__listOrDisplayAllDirectoryContentsInPagerUsingShortListingFormat \
-1 "$@"
}
# Prints name of first file in the directory.
__listFirstFileInDirectory() {
ls "$@" | head -1
}
# Prints name of a newest file in the directory.
__printNameOfNewestFileInDirectory() {
ls -pt "$@" | grep -v / | head -1
}
# Prints name of a random file in the directory.
__printNameOfRandomFileInDirectory() {
ls -pt | grep -v / | sort -R | head -1
}
# Prints all directories in current and sub-directories.
# TODO problem with find: no such file or directory in github.
__printAllSubdirectories() {
find . -name .git -prune -o -type d | __printOrDisplayTextOrFileInPager
}
# Prints all file extensions of files in current and sub-directories.
__printAllFileExtensions() {
find . -type f -name '*.*' | \
sed 's|.*\.||' | \
sort -u | \
__printOrDisplayTextOrFileInPager
}
########
# TREE #
########
# Displays tree structure of current or specified folder, by
# running tree command with:
# * always use colors,
# * ignore .git directories and
# * list directories before files.
__printDirectoryStructure() {
tree "${_TREE_OPTIONS[@]}" "$@" | __printOrDisplayTextOrFileInPager
}
__clearScreenAndprintDirectoryStructure() {
clear
__printDirectoryStructure "$@"
}
######
# CD #
######
# Goes up in the directory hierarchy the specified number of
# levels.
___goUpNumberOfDirectories() {
if [[ "$#" -lt 1 ]]; then
# Needs parameter.
return 1
fi
re='^[1-9]$'
if ! [[ "$1" =~ $re ]] ; then
# Parameter is not a number or it's not the right size.
return 2
fi
i=1
while [[ "$i" -le "$1" ]]; do
cd ..
i=$(($i + 1))
done
}
__goUpOneDirectory() {
___goUpNumberOfDirectories 1
}
__goUpTwoDirectories() {
___goUpNumberOfDirectories 2
}
__goUpThreeDirectories() {
___goUpNumberOfDirectories 3
}
__goUpFourDirectories() {
___goUpNumberOfDirectories 4
}
__goUpFiveDirectories() {
___goUpNumberOfDirectories 5
}
__goUpSixDirectories() {
___goUpNumberOfDirectories 6
}
# Mounts ISO file and cd-s into it.
__mountIsoAndCdInto() {
sudo mkdir /media/"$1"
sudo mount -o loop "$1" /media/"$1"
cd /media/"$1"
}
#########
# FILES #
#########
# Runs cp in interactive mode (asks before it overwrites
# anything).
__copyFilesSafely() {
cp --interactive --verbose "$@"
}
# Runs mv in interactive mode (asks before it overwrites
# anything).
__moveFilesSafely() {
mv --interactive --verbose "$@"
}
# Runs rm in interactive mode (asks you for every file, if you
# really want to delete it). Run with -f option to override
# interactive mode.
__deleteFilesSafely() {
rm --interactive "$@"
}
# Copies whole directory in interactive mode (asks before it
# overwrites anything).
__copyDirectoriesSafely() {
cp --interactive --verbose --archive --recursive "$@"
}
# Moves whole directory in interactive mode (asks before it
# overwrites anything).
__moveDirectoriesSafely() {
mv --interactive --verbose "$@"
}
# Removes whole directory in interactive mode (checks for every
# file if you really want to delete it). Run with -f option to
# override interactive mode.
__deleteDirectoriesSafely() {
rm --interactive --recursive "$@"
}
# Makes directory (and its parent directories if necessary) and
# descends into.
__createDirectoryAndDescendInto() {
mkdir --parents "$1"
cd "$1"
}
# Backups file, by making a copy with '.bak' extension. All
# file's attributes are preserved.
__backupFile() {
sudo cp --preserve "$1"{,.bak}
}
# Switches the contents of two specified files.
__switchContentsOfFiles() {
tempFile=$(mktemp)
sudo cp "$1" "$tempFile"
sudo cp -f --no-preserve=mode,ownership "$2" "$1"
sudo cp -f --no-preserve=mode,ownership "$tempFile" "$2"
}
#######
# PWD #
#######
# If no file specified, prints working directory, else full path
# of the file.
__printWorkingDirectoryOrPathToFile() {
if [[ $# -eq 0 ]]; then
echo "$PWD"
else
echo "$PWD"/"$@"
fi
}
########
# ECHO #
########
# Runs echo.
__printText() {
echo "$@"
}
# Runs echo that interprets backslashed characters (\n,...).
__printTextInterpretingBackslashedCharacters() {
echo -e "$@"
}
# Runs echo that doesn't print new line at the end.
__printTextWithoutTrailingNewline() {
echo -n "$@"
}
#####################
# RUN IN BACKGROUND #
#####################
# Runs command in background. It doesn't hang up if shell
# is closed and it doesn't print output.
__runCommandInBackground() {
nohup "$@" &>/dev/null &
}
complete -F _command __runCommandInBackground
##########
# BASICS #
##########
# Opens this file in Vim.
__editStandardAliases() {
"$EDITOR" ~/.standard_aliases/functions
}
__editUsersStandardRc() {
"$EDITOR" ~/.standardrc
}
__editProjectsStandardRc() {
projectLocation=$(dirname $(readlink ~/.standard_aliases/functions))
"$EDITOR" "$projectLocation"/standard_rc
}
# Runs bash. Run this command for changes to this file to take
# effect!
__startNewBashShell() {
bash "$@"
}
# $1 - function name
# returns - whole function with options variable substituted with
# real options, as defined at the end of standard_rc.
___getFunctionWithExpandedOptions() {
calledFunction=$(type "$1")
# Extract array names in form of "${_LESS_OPTIONS[@]}" from function.
optionsArray=$(
echo "$calledFunction" \
| grep -o '_[A-Z_]*OPTIONS\[@\]' \
| head -n1)
expandedOptions=${!optionsArray}
# Process options by adding backslashes in fornt of slashes, so they
# dont break sed.
expandedOptions=$(echo "$expandedOptions" | sed 's/\//\\\//g')
optionsName=$(echo "$optionsArray" | grep -o '_[A-Z_]*OPTIONS')
echo "$calledFunction" \
| sed "s/...$optionsName\[@\]../$expandedOptions/g" \
| grep --invert-match 'is a function'
}
___printFirstFunctionThatAFunctionCallsAndExpandOptions() {
nameOfCalledFunction=$(
type "$@" \
| grep -A1 '{' \
| grep -o '__[^ ]*')
___getFunctionWithExpandedOptions "$nameOfCalledFunction"
}
# Prints location of specified command, or it's definition, if
# it is an alias. Run this command if you are not sure what an
# alias does!
__printCommandTypeOrDefinition() {
# Checks if command is defined in standardrc, and if so it
# runs type on the command it calls.
standardAliases=$(
grep ':' ~/.standardrc \
| sed 's/:.*$//' \
| tr -d ' ' \
| sed 's/,/\n/g')
if [[ $(echo "$standardAliases" | grep "^$1$") ]]; then
___printFirstFunctionThatAFunctionCallsAndExpandOptions "$1" \
| __printOrDisplayTextOrFileInPager
elif [[ $(echo "$1" | grep '^__') ]]; then
# Also expand options if functin starts with '__' or '___'.
# We'll assume it's a part of standard functions, although it's
# not necessary true.
___getFunctionWithExpandedOptions "$1" \
| __printOrDisplayTextOrFileInPager
else
type "$@" | __printOrDisplayTextOrFileInPager
fi
}
complete -F _command __printCommandTypeOrDefinition
# Runs cat.
__printFileContents() {
cat "$@"
}
# Prints the exit code of the last command.
__printExitCodeOfLastCommand() {
echo $?
}
# Clears the screen.
__clearTheScreen() {
clear
}
# Resets the screen.
__resetTheScreen() {
reset "$@"
}
# Exits shell.
__exitBashShell() {
exit
}
# Opens file with default application for it's file type, and
# runs in background.
__openFileWithDefaultApp() {
__runCommandInBackground xdg-open "$@"
}
# Starts a new terminal, with same working directory.
__openNewTerminalWithSameWorkingDirectory() {
x-terminal-emulator "$@"
}
# Updates file's timestamp, or creates empty file, if it doesn't
# exits.
# By default it doesn't use any options.
__updateFilesTimestampOrCreateNewOne() {
touch "${_TOUCH_OPTIONS[@]}" "$@"
}
# Prints current date and time.
# By default it doesn't use any options.
__printDateAndTime() {
date "${_DATE_OPTIONS[@]}" "$@"
}
# Runs make and sends both 'out' and 'error' streams to pager if
# necessary.
# By default it doesn't use any options.
__runMakeWithPager() {
make "${_MAKE_OPTIONS[@]}" "$@" 2>&1 \
| __printLinesContainingPattern --color=always '^.*error|^.*warning|' \
| __displayTextOrFileInPager
}
# Asigns make completion to command if available.
if [ -f /usr/share/bash-completion/completions/make ]; then
. /usr/share/bash-completion/completions/make
complete -F _make __runMakeWithPager
fi
# Start Nautilus file explorer in background.
__startFileExplorerInBackgroundInWorkingDirectory() {
__runCommandInBackground nautilus .
}
# Runs diff with colors and sends output to pager if necessary.
# By default it doesn't use any options.
__compareFilesLineByLineInColor() {
colordiff "${_DIFF_OPTIONS[@]}" "$@" | __printOrDisplayTextOrFileInPager
}
# Creates executable bash or python script depending on the passed
# filename's extension, or just changes modifiers to executable, if
# file already exists.
__makeFileExecutableOrCreateNewBashOrPythonScript() {
if [[ ! -f "$1" ]]; then
filename=$(basename "$1")
extension="${filename##*.}"
if [[ "$extension" == "py" ]]; then
echo '#!/usr/bin/env python3' >> "$1"
echo '#' >> "$1"
echo "# Usage: python3 $1 " >> "$1"
echo '#' >> "$1"
echo >> "$1"
echo 'from sys import argv, exit' >> "$1"
echo 'from collections import defaultdict, namedtuple' >> "$1"
echo 'from dataclasses import make_dataclass' >> "$1"
echo 'from enum import Enum' >> "$1"
echo 'import functools as ft, itertools as it, operator as op, re' >> "$1"
echo >> "$1"
echo >> "$1"
echo 'def main():' >> "$1"
echo ' pass' >> "$1"
echo >> "$1"
echo >> "$1"
echo '###' >> "$1"
echo '## UTIL' >> "$1"
echo '#' >> "$1"
echo >> "$1"
echo 'def read_file(filename):' >> "$1"
echo " with open(filename, encoding='utf-8') as file:" >> "$1"
echo ' return file.readlines()' >> "$1"
echo >> "$1"
echo >> "$1"
echo "if __name__ == '__main__':" >> "$1"
echo ' main()' >> "$1"
else
echo '#!/bin/bash' >> "$1"
echo '#' >> "$1"
echo "# Usage: ./$1 " >> "$1"
echo '#' >> "$1"
echo >> "$1"
echo '# Stops execution if any command fails.' >> "$1"
echo 'set -eo pipefail' >> "$1"
echo >> "$1"
echo 'main() {'>> "$1"
echo '}'>> "$1"
echo >> "$1"
echo 'main "$@"'>> "$1"
fi
fi
chmod u+x "$@"
}
###########
# HISTORY #
###########
# Searches command history for pattern, or if none is specified,
# prints it whole.
__searchCommandHistoryForPattern() {
if [ "$#" -eq 0 ]; then
history \
| head -n-1 \
| ___printOrDisplayTextOrFileInPagerStartingAtEnd
else
history \
| head -n-1 \
| grep "$@" \
| ___printOrDisplayTextOrFileInPagerStartingAtEnd
fi
}
################
# TEXT EDITORS #
################
# Calls Vim with:
# * open one tab per file.
__editFileWithVim() {
vim "${_VIM_OPTIONS[@]}" "$@"
}
# Runs Vim in read only mode, with:
# * open one tab per file.
__viewFileInVim() {
view "${_VIM_OPTIONS[@]}" "$@"
}
# Runs Nano with this options:
# * enable experimental undo (will most probably crash
# if going deeper than first undo level!!!!!!!!!),
# * autoindent,
# * constantly show the cursor position,
# * log search and replace strings,
# * enable edit of multiple files,
# * treat punctuation as part of words,
# * smooth scrolling and
# * tab size set to 4 spaces.
__editFileWithNano() {
nano "${_NANO_OPTIONS[@]}" "$@"
}
# Runs Nano in view only mode, with this options:
# * enable experimental undo (will most probably crash
# if going deeper than first undo level!!!!!!!!!),
# * autoindent,
# * constantly show the cursor position,
# * log search and replace strings,
# * enable edit of multiple files,
# * treat punctuation as part of words,
# * smooth scrolling and
# * tab size set to 4 spaces.
__viewFileInNano() {
nano --view "${_NANO_OPTIONS[@]}" "$@"
}
# Runs Gedit in background.
# By default it doesn't use any options.
__editFileWithGedit() {
__runCommandInBackground gedit "${_GEDIT_OPTIONS[@]}" "$@"
}
# Runs Sublime Text in background.
__editFileWithSublimeText() {
__runCommandInBackground sublime_text "$@"
}
########
# SUDO #
########
# Runs command as sudo.
__executeCommandAsSuperUser() {
sudo "$@"
}
complete -F _command __executeCommandAsSuperUser
# Executes last command as sudo.
__executeLastCommandAsSuperUser() {
sudo $(history -p \!\!)
}
# Runs cp as superuser in interactive mode (asks before it
# overwrites anything).
__copyFilesSafelyAsSuperUser() {
sudo cp --interactive --verbose "$@"
}
# Runs mv as superuser in interactive mode (asks before it
# overwrites anything).
__moveFilesSafelyAsSuperUser() {
sudo mv --interactive --verbose "$@"
}
# Runs rm as superuser in interactive mode (asks you for every
# file, if you really want to delete it). Run with -f option to
# override interactive mode.
__deleteFilesSafelyAsSuperUser() {
sudo rm --interactive "$@"
}
# Copies whole directory as superuser in interactive mode (asks
# before it overwrites anything).
__copyDirectoriesSafelyAsSuperUser() {
sudo cp --interactive --verbose --archive --recursive "$@"
}
# Moves whole directory as superuser in interactive mode (asks
# before it overwrites anything).
__moveDirectoriesSafelyAsSuperUser() {
sudo mv --interactive --verbose "$@"
}
# Removes whole directory as superuser in interactive mode
# (checks for every file if you really want to delete it). Run
# with -f option to override interactive mode.
__deleteDirectoriesSafelyAsSuperUser() {
sudo rm --interactive --recursive "$@"
}
# Runs less as super user, with:
# * ignore case when searching,
# * do not ring a bell,
# * do not mark empty lines with ~,
# * format prompt as "<page-number>/<all-pages> <filename>" and
# * set tabs to 4 spaces.
__displayTextOrFileInPagerAsSuperUser() {
sudo less "${_LESS_OPTIONS[@]}" "$@"
}
# Runs Vim as super user, with:
# * open one tab per file.
__editFileWithVimAsSuperUser() {
sudoedit "$@"
}
# Runs Vim as super user in read only mode, with:
# * open one tab per file.
__viewFileInVimAsSuperUser() {
sudo view "${_VIM_OPTIONS[@]}" "$@"
}
# Runs Nano as super user with this options:
# * enable experimental undo (will most probably crash
# if going deeper than first undo level!!!!!!!!!),
# * autoindent,
# * constantly show the cursor position,
# * log search and replace strings,
# * enable edit of multiple files,
# * treat punctuation as part of words,
# * smooth scrolling and
# * tab size set to 4 spaces.
__editFileWithNanoAsSuperUser() {
sudo nano "${_NANO_OPTIONS[@]}" "$@"
}
# Runs Gedit as super user.
# By default it doesn't use any options.
__editFileWithGeditAsSuperUser() {
sudo gedit "${_GEDIT_OPTIONS[@]}" "$@"
}
# Alias that puts 'sudo' in front of a command that needs super
# user privileges to run.
__runFdiskAsSuperUser() {
sudo fdisk "$@"
}
__runUpdatedbAsSuperUser() {
sudo updatedb "$@"
}
__runIfconfigAsSuperUser() {
sudo ifconfig "$@"
}
__runTcpdumpAsSuperUser() {
sudo tcpdump "$@"
}
__runRouteAsSuperUser() {
sudo route "$@"
}
__runPm-hibernateAsSuperUser() {
sudo pm-hibernate "$@"
}
__runPm-suspendAsSuperUser() {
sudo pm-suspend "$@"
}
__runShutdownAsSuperUser() {
sudo shutdown "$@"
}
__runFstrimAsSuperUser() {
sudo fstrim "$@"
}
__runApt-getAsSuperUser() {
sudo aptget "$@"
}
__runIwAsSuperUser() {
sudo iw "$@"
}
__runNmapAsSuperUser() {
sudo nmap "$@"
}
__runPartedAsSuperUser() {
sudo parted "$@"
}
__runNtfsundeleteAsSuperUser() {
sudo ntfsundelete "$@"
}
__runLshwAsSuperUser() {
sudo lshw "$@"
}
__runChownAsSuperUser() {
sudo chown "$@"
}
__runMountAsSuperUser() {
sudo mount "$@"
}
#############
# PROCESESS #
#############
# Shows detailed overview of processes (task manager), by running htop.
# By default it doesn't use any options.
__runTerminalTaskManager() {
htop "${_HTOP_OPTIONS[@]}" "$@"
}
# Prints user's processes and sends output to pager if
# necessary, by running ps.
# By default it doesn't use any options.
__printUsersProcesses() {
ps "${_PS_OPTIONS[@]}" "$@" | __printOrDisplayTextOrFileInPager
}
# Prints every process on the system, by running ps with '-e' option.
# By default it doesn't use any other options.
__printAllProcesses() {
ps -e "${_PS_OPTIONS[@]}" "$@" | __printOrDisplayTextOrFileInPager
}
# Prints processes with specified pattern in their names,
# together with their PIDs, by running pgrep, with:
# * list processes name.
__findProcessesWithPartOfName() {
pgrep "${_PGREP_OPTIONS[@]}" "$@" | __printOrDisplayTextOrFileInPager
}
# Asigns pgrep completion to command if available.
if [ -f /usr/share/bash-completion/completions/pgrep ]; then
. /usr/share/bash-completion/completions/pgrep
complete -F _pgrep __findProcessesWithPartOfName
fi
# Sends KILL signal to process with specified PID, instead of
# kill's default signal TERM.
__killProcessWithKillSignal() {
kill -9 "$@"
}
complete -F _pids __killProcessWithKillSignal
# Traces system calls and signals, by running strace, with:
# * print strings of maximum 2000 characters and
# * also trace child processes.
__traceSystemCalls() {
strace "${_STRACE_OPTIONS[@]}" "$@" 2>&1 \
| ___printTextOrFileUntilPageIsFilledThenDisplayInPager
}
complete -F _command __traceSystemCalls
########
# TEXT #
########
# Runs head (prints first 10 lines of file or piped stream).
__printFirstTenLines() {
head "$@"
}
# Prints first line of file or piped stream.
__printFirstLine() {
head -n1 "$@"
}
# Runs tail (prints last 10 lines of file or piped stream).
__printLastTenLines() {
tail "$@"
}
# Prints last line of file or piped stream.