-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
.bash_functions
851 lines (742 loc) · 24.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
# Useful Functions
unload_my_bashrc() {
export PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]ubuntu\[\033[00m\]:[\[\033[01;34m\]\W\[\033[00m\]]\n\n>>> $ '
}
tor() {
sh -c '"${HOME}/Documents/tor-browser_en-US/Browser/start-tor-browser" --detach || ([ ! -x "${HOME}/Documents/tor-browser_en-US/Browser/start-tor-browser" ] && "$(dirname "$*")"/Browser/start-tor-browser --detach)' dummy %k
}
load_my_bashrc() {
source ~/.bashrc
}
nightlight() {
# 1000 — Lowest value (super warm/red)
# 4000 — Default night light on temperature
# 5500 — Balanced night light temperature
# 6500 — Default night light off temperature
# 10000 — Highest value (super cool/blue)
if [ "$1" == 'low' ]; then
VAL=2500
elif [ "$1" == 'bal' ]; then
VAL=5000
else
VAL=$1
fi
gsettings set org.gnome.settings-daemon.plugins.color night-light-enabled false
sleep 0.2
gsettings set org.gnome.settings-daemon.plugins.color night-light-enabled true
gsettings set org.gnome.settings-daemon.plugins.color night-light-temperature $VAL
}
cheatsheet() {
# Cheatsheets https://github.com/chubin/cheat.sh
if [ "$1" == "" ]; then
recho "Usage $0 {filename}"
recho "eg: ${FUNCNAME[0]} ls"
else
curl -L "https://cheat.sh/$1"
fi
}
create-venv() {
create_venv
}
create_venv() {
if command -v virtualenv >/dev/null; then
virtdir=".venv"
printf ">>> Creating Python3 virtualenv: ${virtdir}\n\n"
virtualenv --python="python3" "${virtdir}"
source "${virtdir}/bin/activate"
printf "\n\n>>> Installing a few packages. This will take a few seconds\n\n"
"${virtdir}/bin/pip" install -Uq pip
"${virtdir}/bin/pip" install -Uq \
black \
flake8 \
flake8-black \
ipython['all'] \
isort \
numpy \
pandas \
pre-commit \
pytest \
tqdm \
kube-manifest-lint
FILE=$(find . -type f -name requirements.txt)
if test -s $FILE; then
echo "$FILE exists and not empty"
read -t 5 -p "Hit ENTER if you want install packages in $1 else wait 5 seconds to exit."
if [ $? -eq 0 ]; then
printf ">>> Installing packages from $FILE\n\n"
"${virtdir}/bin/pip" install -U -r $FILE
fi
fi
fi
}
up() {
cd $(printf "%0.s../" $(seq 1 $1))
}
touch_script() {
touch $1 && chmod a+x $1 && subl $1
}
backup() {
FILENAME=$1
cp -v "${FILENAME}" ./"${FILENAME}.bk"
}
killbg() {
kill -9 $(jobs -p)
}
# Calculator
calc() {
# $ calc 1+2 == 3
echo "$*" | bc -l
}
search_replace() {
# Search and replace strings recursively in a given dir
if [ -n "$2" ]; then
if [ -n "$3" ]; then
local path="$3"
else
local path="."
fi
ag -l "$1" "$path" | xargs -I {} -- sed -i "" -e "s%${1//\\/}%$2%g" {}
else
echo "== Usage: gsed search_string replace_string [path = .]"
fi
}
add_alias() {
if [ -n "$2" ]; then
echo "alias $1=\"$2\"" >>~/.bash_aliases
source ~/.bashrc
else
echo "Usage: add_alias <alias> <command>"
fi
}
getbib_from_ieee() {
# Download BibTex from IEEEExplore by ID or URL
INFO="$@"
if [[ "${INFO}" == http* ]]; then
ID=$(echo "${INFO}" | cut -f5 -d '/')
else
ID="${INFO}"
fi
curl -s --data "recordIds=${ID}&download-format=download-bibtex&citations-format=citation-abstract" https://ieeexplore.ieee.org/xpl/downloadCitations >"${ID}_reference".bib
sed -i "s/<br>//g" "${ID}_reference".bib
}
getbib() {
if [ -f "$1" ]; then
# Try to get DOI from pdfinfo or pdftotext output.
doi=$(pdfinfo "$1" | grep -io "doi:.*") ||
doi=$(pdftotext "$1" - 2>/dev/null | grep -io "doi:.*" -m 1) ||
exit 1
else
doi="$1"
fi
# Check crossref.org for the bib citation.
curl -s "http://api.crossref.org/works/${doi}/transform/application/x-bibtex" -w "\\n"
# Check doi2bib.org for the bib citation.
curl -s "https://doi2bib.org/doi2bib?id=${doi}" -w "\\n"
}
sciget() {
# sci-hub.tw
# The first pirate website in the world to provide mass and public access to tens of millions of research papers
curl -O $(curl -s http://sci-hub.tw/"$@" | grep location.href | grep -o "http.*pdf")
if [[ "$@" == "https://ieeexplore.ieee.org/"* ]]; then getbibtex "$@"; fi
}
mkdir_cd() {
# Create a new directory and enter it
mkdir -p "$@" && echo "You are in: $@" && builtin cd "$@" || exit 1
}
rename-to-lowercase() {
# Renames all items in a directory to lower case.
for i in *; do
echo "Renaming $i to ${i,,}"
mv "$i" "${i,,}"
done
}
gitignore() {
# Generate .gitignore
curl -sL "https://www.gitignore.io/api/$@"
}
# Git related functions and aliases
git() {
if [[ "$1" == "flash-back" ]]; then
git-flash-back
elif [[ "$1" == "revert-commit" ]]; then
git-revert-commit
elif [[ "$1" == "pull-all" ]]; then
git-pull-all
elif [[ "$1" == "rename-branch" ]]; then
git-rename-branch
elif [[ "$1" == "fetch-all-branches" ]]; then
git-fetch-all-branches
elif [[ "$1" == "init-repo" ]]; then
git-init-repo
elif [[ "$1" == "create-repo-n-push" ]]; then
git-create-repo-and-push
elif [[ "$1" == "checkout-update-master" ]]; then
git-checkout-update-master
else
# Specifically use hub (wrapper) instead of git.
command hub "$@"
fi
}
git-init-repo() {
git init -q
gitignore venv,python,JupyterNotebooks,SublimeText,VisualStudioCode,vagrant,dotenv >.gitignore
echo "# $(basename "$(pwd)")" > README.md
git add .gitignore README.md
git commit -nm'Add README and .gitignore files <automated msg>'
}
git-create-repo-and-push() {
git create
git push --set-upstream origin $(git symbolic-ref --short HEAD)
}
git-revert-commit() {
# Undo last pushed commit
if [ "$1" == "" ]; then
recho "Usage $0 'commit-hash'"
recho "eg: ${FUNCNAME[0]} '6e9f0998'"
else
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
git reset --hard $1
git push -f origin "$BRANCH"
fi
}
git-flash-back() {
git reflog --date=relative | gawk 'match($0, /HEAD@\{(.+)\}: chec.out: moving from .+ to (.+)/, m) && !branches[m[2]]++ {print m[1] "\t" m[2]} '
}
git-pull-all() {
# Pull all remote refs from repos in the current dir
CUR_DIR=$(pwd)
find -type d -execdir test -d {}/.git \; -print -prune | sort | while read -r DIR; do
builtin cd $DIR &>/dev/null
(git fetch -pa && git pull --allow-unrelated-histories \
origin $(git symbolic-ref --short HEAD)) &>/dev/null &
disown
STATUS=$(git status 2>/dev/null |
awk -v r=${RED} -v y=${YELLOW} -v g=${GREEN} -v b=${BLUE} -v n=${NC} '
/^On branch / {printf(y$3n)}
/^Changes not staged / {printf(g"|?Changes unstaged!"n)}
/^Changes to be committed/ {printf(b"|*Uncommitted changes!"n)}
/^Your branch is ahead of/ {printf(r"|^Push changes!"n)}
')
LAST_UPDATE="${STATUS} | ${LIGHTCYAN}[$(git show -1 --stat | grep ^Date | cut -f4- -d' ')]${NC}"
printf "Repo: \t${DIR} \t\t | ${LAST_UPDATE}\n"
builtin cd - &>/dev/null
done
builtin cd ${CUR_DIR} &>/dev/null
}
backup_my_git_repos() {
# Get a list of all your Git repos in the current directory
FILENAME=~/My-Git-Repos.txt
if [ ! -f $FILENAME ]; then touch $FILENAME; fi
CUR_DIR=$(pwd)
find -type d -execdir test -d {}/.git \; -print -prune | while read -r DIR; do
builtin cd ${DIR} &>/dev/null
echo -e "\n[$(basename $(pwd))]" >>$FILENAME
git config --get remote.origin.url >>$FILENAME
builtin cd - &>/dev/null
done
builtin cd "${CUR_DIR}" &>/dev/null
}
git-rename-branch() {
# Rename current branch with new one and push to remote
if [ "$1" = "help" -o "$1" = "-h" -o "$1" = "--help" -o "$1" = "h" -o "$1" = "" ]; then
recho "Usage $0 new_name'"
recho "This will rename the branch 'error-fixes' into 'syntax-error-fix'"
recho "eg: ${FUNCNAME[0]} 'syntax-error-fix'"
else
new_name=$1
old_name="$(git rev-parse --abbrev-ref HEAD)"
echo "Renaming current branch from ${old_name} to ${new_name}"
git branch -m "${new_name}"
git push origin :"${old_name}"
git push origin "${new_name}":"refs/heads/${new_name}"
fi
}
clone-my-repos() {
# Clone all my repos from file
CLONEDIR=~/GitHub
if [ "$1" == "" ]; then
recho "Usage $0 {filename}"
recho "eg: ${FUNCNAME[0]} My-Git-Repos.txt"
else
while IFS='' read -r repo || [[ -n "$repo" ]]; do
[ ! -d "${CLONEDIR}" ] && mkdir -p "${CLONEDIR}"
echo "Cloning Repo: $repo"
git -C "${CLONEDIR}" clone --depth 5 "$repo"
done <"$1"
fi
}
committer() {
MSG="$@"
# Add file(s), commit with generic message and push to remote
git status | grep "modified:" | cut -f2 -d ":" | tr -s ' ' | while read line; do
git add -f "${line}"
done
FILE=$(command git status | grep "modified:" | cut -f2 -d ":" | tr "\n" " " | xargs)
if [ ! -z "${MSG}" ]; then
# SignOff by username & email, SignOff with PGP and ignore hooks
git commit -s -S -n -m "${MSG}"
else
git commit -s -S -n -m"Updated ${FILE}"
fi
read -t 5 -p "Hit ENTER if you want to push else wait 5 seconds"
[ $? -eq 0 ] && bash -c "git push --no-verify -q -u origin $(git rev-parse --abbrev-ref HEAD) &>/dev/null &disown;"
}
createpr() {
# Push changes and create Pull Request on GitHub
REMOTE="devel"
LABELS="Review Me"
if ! git show-ref --quiet refs/heads/devel; then REMOTE="master"; fi
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
git push -u origin "${BRANCH}" || true
if command -v hub >/dev/null; then
# Check if branch contains a JIRA ticket id.
if echo "${BRANCH}" | grep -q "MT-"; then
REVIEWERS="ajoubertza,amakhaba,bngcebetsha,lanceWilliams,tockards,mamkhari"
echo "Requesting PR Reviewers: ${REVIEWERS}"
hub pull-request --draft -b "${REMOTE}" -h "${BRANCH}" -r "${REVIEWERS}" \
--labels "${LABELS}" --no-edit || hub pull-request \
-b "${REMOTE}" -h "${BRANCH}" -r "${REVIEWERS}" --labels "${LABELS}" --no-edit
else
hub pull-request --draft -b "${REMOTE}" -h "${BRANCH}" --no-edit || hub pull-request \
-b "${REMOTE}" -h "${BRANCH}" --no-edit
fi
else
recho "Failed to create PR, create it Manually"
recho "If you would like to continue install hub: https://github.com/github/hub/"
fi
}
git-url-shortener() {
# GitHub URL shortener
if [ "$1" == "" ]; then
recho "Usage $0 {Custom URL Name} {URL}"
recho "eg: ${FUNCNAME[0]} runme https://raw.githubusercontent.com/blablabla "
else
curl https://git.io/ -i -F "url=${2}" -F "code=${1}"
fi
}
git-fetch-all-branches() {
# Fetch all remote branches
if command -v hub >/dev/null 2>&1; then
/usr/local/bin/hub checkout --detach;
/usr/local/bin/hub fetch origin '+refs/heads/*:refs/heads/*'
else
/usr/bin/git checkout --detach
/usr/bin/git fetch origin '+refs/heads/*:refs/heads/*'
fi
}
git-checkout-update-master() {
# Forcefully checkout master and pull latest changes.
for DIR in $(ls --color=never); do
echo $DIR
pushd $DIR
git checkout -f master && git pull -q origin master &>/dev/null &
disown
popd
done
}
find-file() {
# Find filename
for FILE in $(find . -type f -name "*$1"); do
echo ${FILE}
done
}
ssh() {
# Always ssh with -X
command ssh -X "$@"
}
wrapper() {
# Desktop notification when long running commands complete
start=$(date +%s)
"$@"
[ $(($(date +%s) - start)) -le 15 ] || notify-send "Notification" \
"Long running command \"$(echo $@)\" took $(($(date +%s) - start)) seconds to finish"
}
extract() {
if [ -f $1 ]; then
case $1 in
*.tar.xz) tar -xJf $1 ;;
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) rar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via ${FUNCNAME[0]}" ;;
esac
else
recho "'$1' is not a valid file"
fi
}
find_and_unzip_all() {
find . -name '*.zip' -exec sh -c 'unzip -d "`dirname \"{}\"`" "{}"' ';'
}
open() {
if [ -f $1 ]; then
case $1 in
# List should be expanded.
*.pdf) evince $1 & ;;
*.md) code $1 ;;
*.mp3 | *.mp4 | *.mkv) vlc $1 & ;;
*) xdg-open $1 >>/dev/null ;;
esac
else
xdg-open $1 >>/dev/null
fi
}
compile() {
if [ -f $1 ]; then
case $1 in
# List should be expanded.
*.c) gcc -H -Wall "$1" -o "main" -lm ;;
*.go) go run "$1" ;;
*.py) pycompile -v "$1" ;;
*.tex) latexmk -pdf "$1" ;;
*) recho "'$1' cannot opened via ${FUNCNAME[0]}" ;;
esac
else
recho "'$1' is not a valid file"
fi
}
psgrep() {
if [ ! -z $1 ]; then
echo "Grepping for processes matching $1..."
ps aux | grep $1 | grep -v grep
else
recho "!! Need name to grep for"
fi
}
cd() {
# The 'builtin' keyword allows you to redefine a Bash builtin without
# creating a recursion. Quoting the parameter makes it work in case there are spaces in
# directory names.
builtin cd "$@" && ls -thor
if [ "${PWD}" == "${HOME}/CAM_Work" ]; then
git-pull-all
elif [ "${PWD}" == "${HOME}/Udacity-work" ]; then
unload_my_bashrc;
code .
fi
}
mv-new-files() {
if [ "$1" == "" ]; then
recho "Usage: $0 {from_dir} {to_dir} {no of files}"
recho "eg: ${FUNCNAME[0]} ~/Downloads ~/Videos 3"
else
from_dir=$1
to_dir=$2
no_files=$3
all_files=$(ls -A1tr --color="never" ${from_dir} | tail -$no_files)
for FILE in ${all_files}; do
mv "${from_dir}/${FILE}" $to_dir
done
fi
}
install-pkg() {
echo "Installing package: $@"
if command -v gdebi >/dev/null; then
if [[ "$@" == *"http"* ]]; then
wget -O /tmp/package.deb "$@"
sudo gdebi /tmp/package.deb
else
sudo gdebi $@
fi
else
sudo dpkg --install $@
fi
}
gpg_delete_all_keys() {
for KEY in $(gpg --with-colons --fingerprint | grep "^fpr" | cut -d: -f10); do
gpg --batch --delete-secret-keys "${KEY}"
done
}
disconnect() {
# Disconnect all mounted disks
while IFS= read -r -d '' file; do
fusermount -qzu $file >/dev/null
done < <(find "${HOME}/mnt" -maxdepth 1 -type d -print0)
}
cammount() {
IP="10.8.67.160"
if timeout 2 ping -c 1 -W 2 "${IP}" &>/dev/null; then
sshfs -o reconnect,ServerAliveInterval=5,ServerAliveCountMax=5 \
kat@"${IP}":/ /home/"${USER}"/mnt/cam
else
fusermount -quz /home/"${USER}"/mnt/cam
fi
}
create_project() {
# Easily create a project x in current dir using cookiecutter templates
PACKAGES=("pygithub" "cookiecutter" "platformio")
PACKAGE_DIR=""
export DESCRIPTION="description goes here!"
PYTHON3_PIP="python3 -W ignore::DeprecationWarning -m pip -q --disable-pip-version-check"
IDE="subl"
for pkg in "${PACKAGES[@]}"; do
if bash -c "${PYTHON3_PIP} freeze | grep -i "${pkg}" &>/dev/null &disown;"; then
bash -c "${PYTHON3_PIP} install -q --user -U "${pkg}" &>/dev/null &disown;"
fi
done
read -p "What is the language you using for the (or type of) project? " LANG
if [[ "${LANG}" =~ ^([pP])$thon ]]; then
gecho "Lets build your Python project, Please follow the prompts."
cookiecutter https://github.com/mmphego/cookiecutter-python-package
PACKAGE_DIR=$(ls -tr --color='never' | tail -n1)
export DESCRIPTION=$(grep -oP '(?<=DESCRIPTION = ).*' setup.py)
cd -- "${PACKAGE_DIR}"
elif [[ "${LANG}" =~ ^([uU])$python ]]; then
gecho "Lets build your Micropython project, Please follow the prompts."
cookiecutter https://github.com/mmphego/cookiecutter-micropython
PACKAGE_DIR=$(ls -tr --color='never' | tail -n1)
cd -- "${PACKAGE_DIR}"
export DESCRIPTION=$(grep -oP '(?<=DESCRIPTION = ).*' setup.py)
elif [[ "${LANG}" =~ ^([Aa])$duino ]]; then
gecho "Lets build your Arduino project, Please follow the prompts."
read -p "Enter name of the project directory? " PACKAGE_DIR
read -p "Enter type of board (nodemcu/uno)? " BOARD
read -p "What IDE would you like to use vscode/atom/vim? " IDE
read -p "Enter the description of the project? " DESCRIPTION
export DESCRIPTION="${DESCRIPTION}"
mkdir -p "${PACKAGE_DIR}"
python2 -m platformio init -s -d ${PACKAGE_DIR} -b ${BOARD} --ide ${IDE}
cd -- "${PACKAGE_DIR}"
fi
############################################################
if [[ "${PACKAGE_DIR}" == "$(basename $(pwd))" ]]; then
git init -q
python3 -c """
from configparser import ConfigParser
from pathlib import Path
from os import getenv
from subprocess import check_output
from github import Github
try:
token = check_output(['git', 'config', 'user.token'])
token = token.strip().decode() if type(token) == bytes else token.strip()
except Exception:
p = pathlib.Path('.gitconfig.private')
config.read(p.absolute())
token = config['user']['token']
proj_name = Path.cwd().name
g = Github(token)
user = g.get_user()
user.create_repo(
proj_name,
description=getenv('DESCRIPTION', 'Description goes here!'),
has_wiki=False,
has_issues=True,
auto_init=False)
print('Successfully created repository %s' % proj_name)
"""
git add . >/dev/null 2>&1
git commit -q -nm "Automated commit" >/dev/null 2>&1
git remote add origin "git@github.com:$(git config user.username)/${PACKAGE_DIR}.git" >/dev/null 2>&1
git push -q -u origin master >/dev/null 2>&1
"${IDE}" .
fi
}
create_blog_post() {
if [ "$1" == "" ]; then
recho "Usage: $0 hello world"
recho "eg: ${FUNCNAME[0]} 'Hello world' "
recho "This will create a file with (date)-hello-world"
return
fi
BLOG_DIR=$(locate -b 'mmphego.github.io')
if [ -d "${BLOG_DIR}" ]; then
FILENAME=$@
DATE=$(date +'%Y-%m-%d')
TIME=$(date +'%H:%M:%S')
NEW_POST="${BLOG_DIR}/_posts/${DATE}-${FILENAME// /-}.md"
NEW_POST_IMG="/assets/${DATE}-${FILENAME// /-}.png"
BG_IMG="${BLOG_DIR}/img/new_post_word_cloud.png"
# Titlecase the filename
TITLE=($FILENAME)
TITLE="${TITLE[@]^}"
touch "${NEW_POST}"
tee "${NEW_POST}" <<EOF
---
layout: post
title: "${TITLE}"
date: ${DATE} ${TIME}.000000000 +02:00
tags:
-
-
-
---
# ${TITLE}.
{:refdef: style="text-align: center;"}
![post image]({{ "${NEW_POST_IMG}" | absolute_url }})
{: refdef}
<<TIME TO READ>>
---
# The Story
## TL;DR
## TS;RE
## The How
## The Walk-through
## Reference
- []()
- []()
EOF
if command -v code >/dev/null 2>&1; then
code -n "${NEW_POST}"
else
subl "${NEW_POST}"
fi
recho "Do not forget to Run:"
set -x
generate_wordcloud.py -f "${NEW_POST}" -s "${BG_IMG}"
cp "${BG_IMG}" "${BLOG_DIR}${NEW_POST_IMG}"
set +x
recho "When you are done editing."
else
recho "Could not find blog directory."
fi
}
mv_file_to_dir() {
for file in *.{avi,mp4,mkv}; do
DIR="${file%.*}"
mkdir -p "${DIR}"
mv "${file}" "${DIR}"
done
}
rm_pyc() {
find . -name "*.pyc" -exec rm -f {} \;
find . -name "__pycache__" -exec rm -rf {} \;
}
sync_with_cam() {
if [ "$1" == "" ]; then
recho "Usage: $0 devm"
recho "eg: ${FUNCNAME[0]} devm"
return
fi
if ! command -v entr >/dev/null 2>&1; then
recho "Entr is not installed."
recho "Install entr: http://eradman.com/entrproject/"
exit 1
fi
CONFIG_FILE="${HOME}/.secrets/config.sh"
if [ ! -f "${CONFIG_FILE}" ]; then
recho "Config file doesnt exist."
else
source "${CONFIG_FILE}"
CWD_PATH=$(pwd | cut -d'/' -f5-)
RSYNC_SRC="${LOCAL_DIR}/${CWD_PATH}"
RSYNC_DEST="${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/${CWD_PATH}"
# Download entr:
# https://github.com/eradman/entr
# http://eradman.com/entrproject/
find . | entr rsync -truv \
--exclude-from="$(git worktree list | cut -d' ' -f1)/.gitignore" \
--exclude=".git" \
--progress "${RSYNC_SRC}/" "${RSYNC_DEST}"
fi
}
install() {
# Debian package installer fallback.
sudo apt-get -y --install-recommends install "$@"
ret_code=$?
if [ "$ret_code" == 100 ]; then
echo -e "\nAPT doesn't have the package that you are trying to install, "
echo -e "I will install it using 'snap'\n\n"
sudo snap install "$@"
fi
}
uninstall_pkgs() {
sudo snap remove "$@"
sudo apt-get --purge autoremove "$@"
}
mp3_split_on_silence() {
sox $@ file.mp3 silence 1 1.0 0.2% 1 0.8 0.5% : newfile : restart
}
vid_2_gif() {
if [ "$1" == "" ]; then
recho "Usage $0 filename.mp4"
else
ffmpeg -i "$1" -r 15 -vf scale=720:-1 "$1.gif"
fi
}
gif_2_vid() {
if [ "$1" == "" ]; then
recho "Usage $0 filename.gif"
else
ffmpeg -i "$1" -movflags faststart -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" "${1}.mp4"
fi
}
extract_audio_from_video() {
ffmpeg -i $1 -vn -b:a 320k output-audio.mp3
}
pdf_merge() {
pdftk "$1" "$2" cat output mergedfile.pdf
}
public_ip_open_ports() {
nmap $(curl ifconfig.me)
}
ips() {
IP_RANGE=192.168.1.0/24
if command -v netdiscover >/dev/null 2>&1; then
sudo netdiscover -r $IP_RANGE
else
nmap -sP $IP_RANGE
fi
}
epoch_to_human() {
date -d @"$1"
}
describe_pod()
{
if [ $# -ne 1 ];then
echo "Error: Pod name is missing as input argument"
return 1
fi
pod_name=${1}
kubectl describe pod "${pod_name}" -n \
$(kubectl get pod -A | awk -v pod="$pod_name" -v def=default '$2==pod{ns=$1} END{if(!length(ns))print def; else print ns}')
}
function clean_root {
# Will need English output for processing
LANG=en_GB.UTF-8
## Show free space
df -h /
## Clean apt cache
sudo apt-get update -qq
sudo apt-get -f install
sudo apt-get -y autoremove
sudo apt-get clean
## Remove old versions of snap packages
snap list --all | while read snapname ver rev trk pub notes; do
if [[ $notes = *disabled* ]]; then
sudo snap remove "$snapname" --revision="$rev"
fi
done
## Set snap versions retain settings
if [[ $(snap get system refresh.retain) -ne 2 ]]; then sudo snap set system refresh.retain=2; fi
sudo rm -f /var/lib/snapd/cache/*
## Remove old versions of Linux Kernel
# This one-liner is deprecated since 18.04
# dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs apt-get -y purge
# New 2 lines to remove old kernels
sudo dpkg --list | grep 'linux-image' | awk '{ print $2 }' | sort -V | sed -n '/'"$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")"'/q;p' | xargs sudo apt-get -y purge
sleep 1
sudo dpkg --list | grep 'linux-headers' | awk '{ print $2 }' | sort -V | sed -n '/'"$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")"'/q;p' | xargs sudo apt-get -y purge
## Rotate and delete old logs
sudo /etc/cron.daily/logrotate
sudo find /var/log -type f -iname *.gz -delete
sudo journalctl --rotate
sudo journalctl --vacuum-time=1s
sudo update-grub
## Show free space
df -h /
}
kill-process () {
if [ $# -ne 1 ];then
echo "Error: Process name is missing as input argument"
return 1
fi
kill -9 $(pgrep $1 -d ' ')
}