forked from mathiasbynens/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 49
/
.functions
1579 lines (1384 loc) · 41 KB
/
.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
#!/usr/bin/env bash
# -------------------------------------------------------------------
# err: error message along with a status information
#
# example:
#
# if ! do_something; then
# err "Unable to do_something"
# exit "${E_DID_NOTHING}"
# fi
#
err()
{
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2
}
# -------------------------------------------------------------------
# cd: this will overwrite the default "cd"-command
cd()
{
if [[ "x$*" == "x..." ]]; then
cd ../..
elif [[ "x$*" == "x...." ]]; then
cd ../../..
elif [[ "x$*" == "x....." ]]; then
cd ../../../..
elif [[ "x$*" == "x......" ]]; then
cd ../../../../..
elif [ -d ~/.autoenv ]; then
source ~/.autoenv/activate.sh
autoenv_cd "$@"
else
builtin cd "$@"
fi
}
# -------------------------------------------------------------------
# cdo: cd into the previous (old) working directory
cdo()
{
cd $OLDPWD
}
# -------------------------------------------------------------------
# lc: Convert the parameters or STDIN to lowercase.
lc()
{
if [ $# -eq 0 ]; then
python -c 'import sys; print sys.stdin.read().decode("utf-8").lower()'
else
for i in "$@"; do
echo $i | python -c 'import sys; print sys.stdin.read().decode("utf-8").lower()'
done
fi
}
# -------------------------------------------------------------------
# uc: Convert the parameters or STDIN to uppercase.
uc()
{
if [ $# -eq 0 ]; then
python -c 'import sys; print sys.stdin.read().decode("utf-8").upper()'
else
for i in "$@"; do
echo $i | python -c 'import sys; print sys.stdin.read().decode("utf-8").upper()'
done
fi
}
# -------------------------------------------------------------------
# Call from a local repo to open the repository on github/bitbucket in browser
#
# usage:
repo()
{
local giturl=$(git config --get remote.origin.url \
| sed 's/git@/\/\//g' \
| sed 's/.git$//' \
| sed 's/https://g' \
| sed 's/:/\//g')
if [[ $giturl == "" ]]; then
echo "Not a git repository or no remote.origin.url is set."
else
local gitbranch=$(git rev-parse --abbrev-ref HEAD)
local giturl="https:${giturl}"
if [[ $gitbranch != "master" ]]; then
if echo "${giturl}" | grep -i "bitbucket" > /dev/null ; then
local giturl="${giturl}/branch/${gitbranch}"
else
local giturl="${giturl}/tree/${gitbranch}"
fi
fi
echo $giturl
o $giturl
fi
}
# -------------------------------------------------------------------
# wtfis: Show what a given command really is. It is a combination of "type", "file"
# and "ls". Unlike "which", it does not only take $PATH into account. This
# means it works for aliases and hashes, too. (The name "whatis" was taken,
# and I did not want to overwrite "which", hence "wtfis".)
# The return value is the result of "type" for the last command specified.
#
# usage:
#
# wtfis man
# wtfis vi
#
# source: https://raw.githubusercontent.com/janmoesen/tilde/master/.bash/commands
wtfis()
{
local cmd=""
local type_tmp=""
local type_command=""
local i=1
local ret=0
if [ -n "$BASH_VERSION" ]; then
type_command="type -p"
else
type_command=( whence -p ) # changes variable type as well
fi
if [ $# -eq 0 ]; then
# Use "fc" to get the last command, and use that when no command
# was given as a parameter to "wtfis".
set -- $(fc -nl -1)
while [ $# -gt 0 -a '(' "sudo" = "$1" -o "-" = "${1:0:1}" ')' ]; do
# Ignore "sudo" and options ("-x" or "--bla").
shift
done
# Replace the positional parameter array with the last command name.
set -- "$1"
fi
for cmd; do
type_tmp="$(type "$cmd")"
ret=$?
if [ $ret -eq 0 ]; then
# Try to get the physical path. This works for hashes and
# "normal" binaries.
local path_tmp=$(${type_command} "$cmd" 2>/dev/null)
if [ $? -ne 0 ] || ! test -x "$path_tmp"; then
# Show the output from "type" without ANSI escapes.
echo "${type_tmp//$'\e'/\\033}"
case "$(command -v "$cmd")" in
'alias')
local alias_="$(alias "$cmd")"
# The output looks like "alias foo='bar'" so
# strip everything except the body.
alias_="${alias_#*\'}"
alias_="${alias_%\'}"
# Use "read" to process escapes. E.g. 'test\ it'
# will # be read as 'test it'. This allows for
# spaces inside command names.
read -d ' ' alias_ <<< "$alias_"
# Recurse and indent the output.
# TODO: prevent infinite recursion
wtfis "$alias_" 2>&2 | sed 's/^/ /'
;;
'keyword' | 'builtin')
# Get the one-line description from the built-in
# help, if available. Note that this does not
# guarantee anything useful, though. Look at the
# output for "help set", for instance.
help "$cmd" 2>/dev/null | {
local buf line
read -r line
while read -r line; do
buf="$buf${line/. */.} "
if [[ "$buf" =~ \.\ $ ]]; then
echo "$buf"
break
fi
done
}
;;
esac
else
# For physical paths, get some more info.
# First, get the one-line description from the man page.
# ("col -b" gets rid of the backspaces used by OS X's man
# to get a "bold" font.)
(COLUMNS=10000 man "$(basename "$path_tmp")" 2>/dev/null) | col -b | \
awk '/^NAME$/,/^$/' | {
local buf=""
local line=""
read -r line
while read -r line; do
buf="$buf${line/. */.} "
if [[ "$buf" =~ \.\ $ ]]; then
echo "$buf"
buf=''
break
fi
done
[ -n "$buf" ] && echo "$buf"
}
# Get the absolute path for the binary.
local full_path_tmp="$(
cd "$(dirname "$path_tmp")" \
&& echo "$PWD/$(basename "$path_tmp")" \
|| echo "$path_tmp"
)"
# Then, combine the output of "type" and "file".
local fileinfo="$(file "$full_path_tmp")"
echo "${type_tmp%$path_tmp}${fileinfo}"
# Finally, show it using "ls" and highlight the path.
# If the path is a symlink, keep going until we find the
# final destination. (This assumes there are no circular
# references.)
local paths_tmp=("$path_tmp")
local target_path_tmp="$path_tmp"
while [ -L "$target_path_tmp" ]; do
target_path_tmp="$(readlink "$target_path_tmp")"
paths_tmp+=("$(
# Do some relative path resolving for systems
# without readlink --canonicalize.
cd "$(dirname "$path_tmp")"
cd "$(dirname "$target_path_tmp")"
echo "$PWD/$(basename "$target_path_tmp")"
)")
done
local ls="$(command ls -fdalF "${paths_tmp[@]}")"
echo "${ls/$path_tmp/$'\e[7m'${path_tmp}$'\e[27m'}"
fi
fi
# Separate the output for all but the last command with blank lines.
[ $i -lt $# ] && echo
let i++
done
return $ret
}
# -------------------------------------------------------------------
# whenis: Try to make sense of the date. It supports everything GNU date knows how to
# parse, as well as UNIX timestamps. It formats the given date using the
# default GNU date format, which you can override using "--format='%x %y %z'.
#
# usage:
#
# $ whenis 1234567890 # UNIX timestamps
# Sat Feb 14 00:31:30 CET 2009
#
# $ whenis +1 year -3 months # relative dates
# Fri Jul 20 21:51:27 CEST 2012
#
# $ whenis 2011-10-09 08:07:06 # MySQL DATETIME strings
# Sun Oct 9 08:07:06 CEST 2011
#
# $ whenis 1979-10-14T12:00:00.001-04:00 # HTML5 global date and time
# Sun Oct 14 17:00:00 CET 1979
#
# $ TZ=America/Vancouver whenis # Current time in Vancouver
# Thu Oct 20 13:04:20 PDT 2011
#
# For more info, check out http://kak.be/gnudateformats.
whenis()
{
# Default GNU date format as seen in date.c from GNU coreutils.
local format='%a %b %e %H:%M:%S %Z %Y'
if [[ "$1" =~ ^--format= ]]; then
format="${1#--format=}"
shift
fi
# Concatenate all arguments as one string specifying the date.
local date="$*"
if [[ "$date" =~ ^[[:space:]]*$ ]]; then
date='now'
elif [[ "$date" =~ ^[0-9]{13}$ ]]; then
# Cut the microseconds part.
date="${date:0:10}"
fi
# Use GNU date in all other situations.
[[ "$date" =~ ^[0-9]+$ ]] && date="@$date"
date -d "$date" +"$format"
}
# -------------------------------------------------------------------
# box: a function to create a box of '=' characters around a given string
#
# usage: box 'testing'
box()
{
local t="$1xxxx"
local c=${2:-"#"}
echo ${t//?/$c}
echo "$c $1 $c"
echo ${t//?/$c}
}
# -------------------------------------------------------------------
# htmlEntityToUTF8: convert html-entity to UTF-8
htmlEntityToUTF8()
{
if [ $# -eq 0 ]; then
echo "Usage: htmlEntityToUTF8 \"▽\""
return 1
else
echo $1 | recode html..UTF8
fi
}
# -------------------------------------------------------------------
# UTF8toHtmlEntity: convert UTF-8 to html-entity
UTF8toHtmlEntity()
{
if [ $# -eq 0 ]; then
echo "Usage: UTF8toHtmlEntity \"♥\""
return 1
else
echo $1 | recode UTF8..html
fi
}
# -------------------------------------------------------------------
# optiImages: optimized images (png/jpg) in the current dir + sub-dirs
#
# INFO: use "grunt-contrib-imagemin" for websites!
optiImages()
{
find . -iname '*.png' -exec optipng -o7 {} \;
find . -iname '*.jpg' -exec jpegoptim --force {} \;
}
# -------------------------------------------------------------------
# Get colors in manual pages
man()
{
env \
LESS_TERMCAP_mb=$(printf "\e[1;31m") \
LESS_TERMCAP_md=$(printf "\e[1;31m") \
LESS_TERMCAP_me=$(printf "\e[0m") \
LESS_TERMCAP_se=$(printf "\e[0m") \
LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
LESS_TERMCAP_ue=$(printf "\e[0m") \
LESS_TERMCAP_us=$(printf "\e[1;32m") \
man "$@"
}
# -------------------------------------------------------------------
# lman: Open the manual page for the last command you executed.
lman()
{
local cmd
set -- $(fc -nl -1)
while [ $# -gt 0 -a '(' "sudo" = "$1" -o "-" = "${1:0:1}" ')' ]; do
shift
done
cmd="$(basename "$1")"
man "$cmd" || help "$cmd"
}
# -------------------------------------------------------------------
# testConnection: check if connection to google.com is possible
#
# usage:
# testConnection 1 # will echo 1 || 0
# testConnection # will return 1 || 0
testConnection()
{
local tmpReturn=1
$(wget --tries=2 --timeout=2 www.google.com -qO- &>/dev/null 2>&1)
if [ $? -eq 0 ]; then
tmpReturn=0
else
tmpReturn=1
fi
if [ "$1" ] && [ $1 -eq 1 ]; then
echo $tmpReturn
else
return $tmpReturn
fi
}
# -------------------------------------------------------------------
# netstat_used_local_ports: get used tcp-ports
netstat_used_local_ports()
{
netstat -atn \
| awk '{printf "%s\n", $4}' \
| grep -oE '[0-9]*$' \
| sort -n \
| uniq
}
# -------------------------------------------------------------------
# netstat_free_local_port: get one free tcp-port
netstat_free_local_port()
{
# didn't work with zsh / bash is ok
#read lowerPort upperPort < /proc/sys/net/ipv4/ip_local_port_range
for port in $(seq 32768 61000); do
for i in $(netstat_used_local_ports); do
if [[ $used_port -eq $port ]]; then
continue
else
echo $port
return 0
fi
done
done
return 1
}
# -------------------------------------------------------------------
# connection_overview: get stats-overview about your connections
netstat_connection_overview()
{
netstat -nat \
| awk '{print $6}' \
| sort \
| uniq -c \
| sort -n
}
# -------------------------------------------------------------------
# nice mount (http://catonmat.net/blog/another-ten-one-liners-from-commandlingfu-explained)
#
# displays mounted drive information in a nicely formatted manner
mount_info()
{
(echo "DEVICE PATH TYPE FLAGS" && mount | awk '$2="";1') \
| column -t;
}
# -------------------------------------------------------------------
# sniff: view HTTP traffic
#
# usage: sniff [eth0]
sniff()
{
if [ $1 ]; then
local device=$1
else
local device='eth0'
fi
sudo ngrep -d ${device} -t '^(GET|POST) ' 'tcp and port 80'
}
# -------------------------------------------------------------------
# httpdump: view HTTP traffic
#
# usage: httpdump [eth1]
httpdump()
{
if [ $1 ]; then
local device=$1
else
local device='eth0'
fi
sudo tcpdump -i ${device} -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\"
}
# -------------------------------------------------------------------
# iptablesBlockIP: block a IP via "iptables"
#
# usage: iptablesBlockIP 8.8.8.8
iptablesBlockIP()
{
if [ $# -eq 0 ]; then
echo "Usage: iptablesBlockIP 123.123.123.123"
return 1
else
sudo iptables -A INPUT -s $1 -j DROP
fi
}
# -------------------------------------------------------------------
# ips: get the local IP's
ips()
{
ifconfig | grep "inet " | awk '{ print $2 }' | cut -d ":" -f 2
}
# -------------------------------------------------------------------
# cleanTheSystem: purge old config, kernel, trash etc. from Ubuntu / Debian
#
# WARNING: take a look on what the package-manager will do
cleanTheSystem()
{
local OLDCONF=$(dpkg -l | grep "^rc" | awk '{print $2}')
local CURKERNEL=$(uname -r | sed 's/-*[a-z]//g' | sed 's/-386//g' | sed 's/-164//g')
local LINUXPKG="linux-(image|headers|ubuntu-modules|restricted-modules)"
local METALINUXPKG="linux-(image|headers|restricted-modules)-(generic|i386|amd64|server|common|rt|xen)"
local OLDKERNELS=$(dpkg -l | awk '{print $2}' | command grep -E $LINUXPKG | grep -vE $METALINUXPKG | grep -v $CURKERNEL)
echo -e $COLOR_YELLOW"clear ".deb"-cache ..."$COLOR_NO_COLOR
sudo aptitude autoclean
echo -e $COLOR_RED"remove not needed packages ..."$COLOR_NO_COLOR
sudo apt-get autoremove
echo -e $COLOR_YELLOW"remove old config-files..."$COLOR_NO_COLOUR
sudo aptitude purge $OLDCONF
echo -e $COLOR_YELLOW"remove old kernels ..."$COLOR_NO_COLOUR
sudo aptitude purge $OLDKERNELS
echo -e $COLOR_YELLOW"clean trash ..."$COLOR_NO_COLOUR
sudo rm -rf /home/*/.local/share/Trash/*/** &> /dev/null
sudo rm -rf /root/.local/share/Trash/*/** &> /dev/null
echo -e $COLOR_YELLOW"... everything is clean!!!"$COLOR_NO_COLOUR
}
# -------------------------------------------------------------------
# extract: extract of compressed-files
extract()
{
if [ -f $1 ] ; then
local lower=$(lc $1)
case $lower in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar e $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.lha) lha e $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via >extract<"
return 1 ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# -------------------------------------------------------------------
# os-info: show some info about your system
os-info()
{
lsb_release -a
uname -a
if [ -z /etc/lsb-release ]; then
cat /etc/lsb-release;
fi;
if [ -z /etc/issue ]; then
cat /etc/issue;
fi;
if [ -z /proc/version ]; then
cat /proc/version;
fi;
}
# -------------------------------------------------------------------
# command_exists: check if a command exists
command_exists()
{
return type "$1" &> /dev/null ;
}
# -------------------------------------------------------------------
# stripspace: strip unnecessary whitespace from file
stripspace()
{
if [ $# -eq 0 ]; then
echo "Usage: stripspace FILE"
exit 1
else
local tempfile=mktemp
git stripspace < "$1" > tempfile
mv tempfile "$1"
fi
}
# -------------------------------------------------------------------
# battery_life : Echo the percentage of battery life remaining
battery_life()
{
local life=$(acpi -b | cut -d "," -f 2)
# NOTE: the trailing % is stripped
echo ${life%\%}
}
# -------------------------------------------------------------------
# battery_indicator: echo a indicator for your battery-time
battery_indicator()
{
local num=$(battery_life)
if [ $num -gt 95 ]; then
# 95-100% remaining : GREEN
echo -e "${COLOR_GREEN}♥♥♥♥♥♥${COLOR_NO_COLOUR}"
elif [ $num -gt 85 ]; then
# 85-95% remaining : GREEN
echo -e "${COLOR_GREEN}♥♥♥♥♥♡${COLOR_NO_COLOUR}"
elif [ $num -gt 65 ]; then
# 65-85% remaining : GREEN
echo -e "${COLOR_GREEN}♥♥♥♥♡♡${COLOR_NO_COLOUR}"
elif [ $num -gt 45 ]; then
# 45-65% remaining : GREEN
echo -e "${COLOR_GREEN}♥♥♥♡♡♡${COLOR_NO_COLOUR}"
elif [ $num -gt 25 ]; then
# 25-45% remaining : GREEN
echo -e "${COLOR_GREEN}♥♥♡♡♡♡${COLOR_NO_COLOUR}"
elif [ $num -gt 10 ]; then
# 11-25% remaining : YELLOW
echo -e "${COLOR_YELLOW}♥♡♡♡♡♡${COLOR_NO_COLOUR}"
else
# 0-10% remaining : RED
echo -e "${COLOR_RED}♥♡♡♡♡♡${COLOR_NO_COLOUR}"
fi
}
# -------------------------------------------------------------------
# logssh: establish ssh connection + write a logfile
logssh()
{
ssh $1 | tee sshlog
}
# -------------------------------------------------------------------
# givedef: shell function to define words
# http://vikros.tumblr.com/post/23750050330/cute-little-function-time
givedef()
{
if [ $# -ge 2 ]; then
echo "givedef: too many arguments" >&2
return 1
else
curl --silent "dict://dict.org/d:$1"
fi
}
# -------------------------------------------------------------------
# lsssh: pretty print all established SSH connections
lsssh ()
{
local ip=""
local domain=""
local conn=""
lsof -i4 -s TCP:ESTABLISHED -n | grep '^ssh' | while read conn; do
ip=$(echo $conn | grep -oE '\->[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[^ ]+')
ip=${ip/->/}
domain=$(dig -x ${ip%:*} +short)
domain=${domain%.}
# display nonstandard port if relevant
printf "%s (%s)\n" $domain ${ip/:ssh}
done | column -t
}
# -------------------------------------------------------------------
# WARNING -> replace: changes multiple files at once
replace()
{
if [ $3 ]; then
find $1 -type f -exec sed -i 's/$2/$3/g' {} \;
else
echo "Missing argument"
exit 1
fi
}
# -------------------------------------------------------------------
# calc: Simple calculator
# usage: e.g.: 3+3 || 6*6/2
calc()
{
local result=""
result="$(printf "scale=10;$*\n" | bc --mathlib | tr -d '\\\n')"
# └─ default (when `--mathlib` is used) is 20
#
if [[ "$result" == *.* ]]; then
# improve the output for decimal numbers
printf "$result" |
sed -e 's/^\./0./' `# add "0" for cases like ".5"` \
-e 's/^-\./-0./' `# add "0" for cases like "-.5"`\
-e 's/0*$//;s/\.$//' # remove trailing zeros
else
printf "$result"
fi
printf "\n"
}
# -------------------------------------------------------------------
# mkd: Create a new directory and enter it
mkd()
{
mkdir -p "$@" && cd "$_"
}
# -------------------------------------------------------------------
# mkf: Create a new directory, enter it and create a file
#
# usage: mkf /tmp/lall/foo.txt
mkf()
{
mkd $(dirname "$@") && touch $@
}
# -------------------------------------------------------------------
# rand_int: use "urandom" to get random int values
#
# usage: rand_int 8 --> e.g.: 32245321
rand_int()
{
if [ $1 ]; then
local length=$1
else
local length=16
fi
tr -dc 0-9 < /dev/urandom | head -c${1:-${length}}
}
# -------------------------------------------------------------------
# passwdgen: a password generator
#
# usage: passwdgen 8 --> e.g.: f4lwka_2f
passwdgen()
{
if [ $1 ]; then
local length=$1
else
local length=16
fi
tr -dc A-Za-z0-9_ < /dev/urandom | head -c${1:-${length}}
}
# -------------------------------------------------------------------
# targz: Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
targz()
{
local tmpFile="${@%/}.tar";
tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1;
local size=$(
stat -f"%z" "${tmpFile}" 2> /dev/null; # OS X `stat`
stat -c"%s" "${tmpFile}" 2> /dev/null; # GNU `stat`
);
local cmd="";
if (( size < 52428800 )) && hash zopfli 2> /dev/null; then
# the .tar file is smaller than 50 MB and Zopfli is available; use it
cmd="zopfli";
else
if hash pigz 2> /dev/null; then
cmd="pigz";
else
cmd="gzip";
fi;
fi;
echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…";
"${cmd}" -v "${tmpFile}" || return 1;
[ -f "${tmpFile}" ] && rm "${tmpFile}";
local zippedSize=$(
stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # OS X `stat`
stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
);
echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}
# -------------------------------------------------------------------
# duh: Sort the "du"-command output and use human-readable units.
duh()
{
local unit=""
local size=""
du -k "$@" | sort -n | while read size fname; do
for unit in KiB MiB GiB TiB PiB EiB ZiB YiB; do
if [ "$size" -lt 1024 ]; then
echo -e "${size} ${unit}\t${fname}"
break
fi
size=$((size/1024))
done
done
}
# -------------------------------------------------------------------
# fs: Determine size of a file or total size of a directory
fs()
{
if du -b /dev/null > /dev/null 2>&1; then
local arg=-sbh
else
local arg=-sh
fi
if [[ -n "$@" ]]; then
du $arg -- "$@"
else
du $arg .[^.]* ./*
fi
}
# -------------------------------------------------------------------
# ff: displays all files in the current directory (recursively)
ff()
{
find . -type f -iname '*'$*'*' -ls
}
# -------------------------------------------------------------------
# fstr: find text in files
fstr()
{
OPTIND=1
local case=""
local usage="fstr: find string in files.
Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
while getopts :it opt
do
case "$opt" in
i) case="-i " ;;
*) echo "$usage"; return;;
esac
done
shift $(( $OPTIND - 1 ))
if [ "$#" -lt 1 ]; then
echo "$usage"
return 1
fi
find . -type f -name "${2:-*}" -print0 \
| xargs -0 egrep --color=auto -Hsn ${case} "$1" 2>&- \
| more
}
# -------------------------------------------------------------------
# file_backup_compressed: create a compressed backup (with date)
# in the current dir
#
# usage: file_backup_compressed test.txt
file_backup_compressed()
{
if [ $1 ]; then
if [ -z $1 ]; then
echo "$1: not found"
return 1
fi
tar czvf "./$(basename $1)-$(date +%y%m%d-%H%M%S).tar.gz" "$1"
else
echo "Missing argument"
return 1
fi
}
# -------------------------------------------------------------------
# file_backup: creating a backup of a file (with date)
file_backup()
{
for FILE ; do
[[ -e "$1" ]] && cp "$1" "${1}_$(date +%Y-%m-%d_%H-%M-%S)" || echo "\"$1\" not found." >&2
done
}
# -------------------------------------------------------------------
# file_information: output information to a file
file_information()
{
if [ $1 ]; then
if [ -z $1 ]; then
echo "$1: not found"
return 1
fi
echo $1
ls -l $1
file $1
ldd $1
else
echo "Missing argument"
return 1
fi
}
# -------------------------------------------------------------------
# dataurl: create a data URL from a file
dataurl()
{
local mimeType=$(file -b --mime-type "$1")
if [[ $mimeType == text/* ]]; then
mimeType="${mimeType};charset=utf-8"
fi
echo "data:${mimeType};base64,$(openssl base64 -in "$1" | tr -d '\n')"
}
# -------------------------------------------------------------------
# gitio: create a git.io short URL
gitio()
{
if [ -z "${1}" ]; then
echo "Usage: \`gitio github-url-or-shortcut\`"
return 1
fi
local url
local code
if [[ "$1" =~ "https:" ]]; then
url=$1
else
url="https://github.com/${1}"
fi
code=$(curl_post -k https://git.io/create -F "url=${url}")
echo https://git.io/${code}
}
# -------------------------------------------------------------------
# shorturl: Create a short URL
shorturl()
{
if [ -z "${1}" ]; then
echo "Usage: \`shorturl url\`"
return 1
fi
curl -s https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": '\"$1\"'}' | grep id | cut -d '"' -f 4
}
# -------------------------------------------------------------------
# server: Start an HTTP server from a directory, optionally specifying the port
server()
{
local free_port=$(netstat_free_local_port)
local port="${1:-${free_port}}"
sleep 1 && o "http://localhost:${port}/" &
# Set the default Content-Type to `text/plain` instead of `application/octet-stream`
# And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port"
}
# -------------------------------------------------------------------
# phpserver: Start a PHP server from a directory, optionally specifying 2x $_ENV and ip:port
# (Requires PHP 5.4.0+.)
#
# usage:
# phpserver [port=auto] [ip=127.0.0.1] [FOO_1=BAR_1] [FOO_2=BAR_2]
phpserver()
{
local free_port=$(netstat_free_local_port)
local port="${1:-${free_port}}"
local ip="${2:-127.0.0.1}"
if [ $3 ] && [ $4 ]; then
export ${3}=${4}