forked from mathiasbynens/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.functions
999 lines (898 loc) · 29.7 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
#!/usr/bin/env bash
# Create a new directory and enter it
function mkd() {
mkdir -p "$@" && cd "$_";
}
# Change working directory to the top-most Finder window location
function cdf() { # short for `cdfinder`
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')";
}
# Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
function targz() {
local tmpFile="${@%/}.tar";
tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1;
size=$(
stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS `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}";
zippedSize=$(
stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS `stat`
stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
);
echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}
# Determine size of a file or total size of a directory
function 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;
}
# Use Git’s colored diff when available
hash git &>/dev/null;
if [ $? -eq 0 ]; then
function diff() {
git diff --no-index --color-words "$@";
}
fi;
# Create a data URL from a file
function 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')";
}
# Create a git.io short URL
function gitio() {
if [ -z "${1}" -o -z "${2}" ]; then
echo "Usage: \`gitio slug url\`";
return 1;
fi;
curl -i https://git.io/ -F "url=${2}" -F "code=${1}";
}
# Start an HTTP server from a directory, optionally specifying the port
function server() {
local port="${1:-8000}";
sleep 1 && open "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";
}
# Settings, functions and aliases for commands
# =============================================================================
# OS X's file system is case-insensitive by default, so use aliases to get
# "GET"/"HEAD"/… working. (Otherwise "HEAD" would execute "/usr/bin/head".)
[[ "$OSTYPE" =~ ^darwin ]] && for method in GET HEAD POST PUT DELETE TRACE OPTIONS; do
alias "$method"="/usr/bin/lwp-request -m $method";
done;
# Confirm before overwriting
# -----------------------------------------------------------------------------
# I know it is bad practice to override the default commands, but this is for
# my own safety. If you really want the original "instakill" versions, you can
# still use "command rm" or "/bin/rm" inside your commands, aliases, functions
# or scripts.
alias cp='cp -i';
alias mv='mv -i';
alias rm='rm -i';
# Editors and pagers
# -----------------------------------------------------------------------------
alias nano='nano -w';
alias pico='nano';
alias vi='vim';
export EDITOR='atom';
# Make sure "view" as-is works when stdin is not a terminal and prevent the
# normal ensuing keyboard input chaos.
function view {
local args=("$@");
if ! [ -t /dev/stdin ] && ! (($#)); then
echo 'Warning: Input is not from a terminal. Forcing "view -".';
args=('-');
fi;
command view "${args[@]}";
}
export PAGER='less --quit-if-one-screen --no-init --ignore-case --RAW-CONTROL-CHARS --quiet --dumb';
# Make "less" transparently unpack archives etc.
if [ -x /usr/bin/lesspipe ]; then
eval $(/usr/bin/lesspipe);
elif type -t lesspipe.sh > /dev/null; then
# MacPorts recommended "/opt/local/bin/lesspipe.sh", but this is more
# portable for people that have it in another directory in their $PATH.
eval $(lesspipe.sh);
fi;
# Edit and reload the profile.
function pro {
#vi +3tabn -p ~/.bash_profile ~/.bash/{shell,commands,prompt,extra};
source ~/.bash_profile;
}
# Colors
# -----------------------------------------------------------------------------
# Always use colour output for "ls".
if [[ "$OSTYPE" =~ ^darwin ]]; then
alias ls='command ls -G';
export LSCOLORS=ExFxCxDxBxegedabagacad
else
alias ls='command ls --color';
export LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:';
fi;
# Utilities
# -----------------------------------------------------------------------------
# Open the manual page for the last command you executed.
function lman {
set -- $(fc -nl -1);
while [ $# -gt 0 -a '(' "sudo" = "$1" -o "-" = "${1:0:1}" ')' ]; do
shift;
done;
cmd="$(basename "$1")";
man "$cmd" || help "$cmd";
}
# OS X has no "md5sum", so use "md5" as a fall-back.
type -t md5sum > /dev/null || alias md5sum='md5';
# Version control
# -----------------------------------------------------------------------------
# Use "colordiff" or "highlight" to colour diffs.
if type -t colordiff > /dev/null; then
alias difflight='colordiff | less -XFIRd';
elif type -t highlight > /dev/null; then
alias difflight='highlight --dark-red ^-.* | highlight --dark-green ^+.* | highlight --yellow ^Only.* | highlight --yellow ^Files.*differ$ | less -XFIRd';
else
alias difflight='less -XFIRd';
fi;
# Git autocompletion.
[ -f ~/.git-completion.bash ] && source ~/.git-completion.bash;
# Show the current Git branch, if any.
# (This is useful in the shell prompt.)
function git-show-branch {
branch="$(git symbolic-ref -q HEAD 2>/dev/null)";
ret=$?;
case $ret in
0) echo "(${branch##*/})";;
1) echo '(no branch)';;
128) echo -n;;
*) echo "[unknown git exit code: $ret]";;
esac;
return $ret;
}
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# THE FUNCTIONS BELOW SHOULD BE MOVED TO SEPARATE SCRIPTS INSIDE ~/bin.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Utilities
# -----------------------------------------------------------------------------
# Show a unified diff, colourised if possible and paged if necessary.
function udiff {
type -t colordiff > /dev/null \
&& local command=colordiff \
|| local command=diff;
"$command" -wU4 -x .svn "$@" | less -XFIRd;
return ${PIPESTATUS[0]};
}
# Move the given file(s) to the Trash.
function trash {
local path;
for path; do
# Make relative paths "absolutey".
[ "${path:0:1}" = '/' ] || path="$PWD/$1";
# Execute the AppleScript to nudge Finder.
echo "$(cat <<-EOD
tell application "Finder"
delete POSIX file "${path//\"/\"}"
end
EOD)" | osascript;
done;
}
# Show the given file(s) in the Finder.
function show {
# Default to the current directory.
[ $# -eq 0 ] && set -- .;
# Build the array of paths for AppleScript.
local path paths=();
for path; do
# Make sure each path exists.
if ! [ -e "$path" ]; then
echo "show: $path: No such file or directory";
continue;
fi;
# Crappily re-implement "readlink -f" ("realpath") for Darwin.
# (The "cd ... > /dev/null" hides CDPATH noise.)
[ -d "$path" ] \
&& path="$(cd "$path" > /dev/null && pwd)" \
|| path="$(cd "$(dirname "$path")" > /dev/null && \
echo "$PWD/$(basename "$path")")";
# Use the "POSIX file" AppleScript syntax.
paths+=("POSIX file \"${path//\"/\"}\"");
done;
[ "${#paths[@]}" -eq 0 ] && return;
# Group all output to pipe through osacript.
{
echo 'tell application "Finder"';
echo -n 'select {'; # "reveal" would select only the last file.
for ((i = 0; i < ${#paths[@]}; i++)); do
echo -n "${paths[$i]}";
[ $i -lt $(($# - 1)) ] && echo -n ', '; # Ugly array.join()...
done;
echo '}';
echo 'activate';
echo 'end tell';
} | osascript;
}
# Use "hd" for the canonical hex dump. (Some systems have this symlinked.)
type -t hd > /dev/null || alias hd='hexdump -C';
# Backups
# -----------------------------------------------------------------------------
# Back up the given files and directories using an incremental backup
# that looks like a full backup, like Time Machine does.
function backup () {(
# Backup format.
local backup_dir="$HOME/backups";
local date_format='%Y-%m-%d-%H-%M-%S';
# Usage.
if [ $# -eq 0 -o "$1" = '--help' ] || [ $# -eq 1 -a "$1" = '--' ]; then
echo 'Usage: backup [[USER@]HOST:]FILE...';
echo;
echo "Back up the given files and directories to $backup_dir/$(date +"$date_format")";
[ "$1" = '--' ] && shift;
[ $# -gt 0 ];
exit $?;
fi;
# Skip the "enough with the options; it's files only from now on" delimiter "--".
[ "$1" = '--' ] && shift;
# Loop the command-line arguments.
local path i=0;
for path; do
# Update the backup directory timestamp for each file being backed up.
local curr_date="$(date +"$date_format")";
# Check if this is a remote source.
! [[ "$path" =~ ^([^/]+):(.*) ]];
is_remote=$?;
# Determine the full source path, source location and target path.
# For local files, the source path and location are the same. For
# remote files, the location is [user@]host:path.
if [ $is_remote -eq 1 ]; then
# For SSH sources, use SSH to find the full path.
host="${BASH_REMATCH[1]}";
local source_path="$(ssh "$host" "$(printf "$(cat <<-'EOD'
host=%q;
path=%q;
if ! [ -z "$path" -o -e "$path" ]; then
echo "$host:$path does not exist." 1>&2;
exit 1;
fi;
{ [ -d "$path" ] && cd -- "$path" && pwd; } || { cd -- "$(dirname -- "$path")" && echo "$PWD/$(basename -- "$path")"; }
EOD)" "$host" "${BASH_REMATCH[2]}")")" || exit 1;
local source_location="$host:$source_path";
local source_path="/ssh=$host$source_path";
elif [ -z "$path" -o -e "$path" ]; then
# For local sources, go to the directory or the file's parent directory and use the working directory.
local source_path="$({ [ -d "$path" ] && cd -- "$path" && pwd; } || { cd -- "$(dirname -- "$path")" && echo "$PWD/$(basename -- "$path")"; })";
local source_location="$source_path";
else
echo "$path does not exist." 1>&2;
exit 1;
fi;
# Determine the target directory for the current backup.
local curr_backup="$backup_dir/$curr_date$source_path";
# if [ $is_remote -eq 1 ]; then
local curr_backup_dir="$(dirname "$curr_backup")";
local curr_backup_dir="$curr_backup";
# Check for previous backups.
local prev_backup='';
shopt -s nullglob;
for prev_backup in "$backup_dir/"*"$source_path"; do
:
done;
# XXX debug delme
for x in path is_remote source_path source_location curr_backup curr_backup_dir prev_backup; do printf $'%12s: "%s"\n' "$x" "${!x}"; done
# Back up using rsync, hard-linking unchanged files to the previous backup, if any.
mkdir -p "$curr_backup_dir";
if [ "$(basename "$source_path")" = "$path" ]; then
echo "Now backing up: \"$path\"";
else
echo "Now backing up: \"$path\" (\"$source_path\")";
fi;
echo "Backing up to: \"$curr_backup\"";
if [ -z "$prev_backup" ]; then
echo 'Previous backup: (none)';
echo;
echo rsync --itemize-changes --archive -- "$source_location" "$curr_backup_dir";
else
echo "Previous backup: \"$prev_backup\"";
echo;
echo rsync --itemize-changes --archive --link-dest="$(dirname "$prev_backup")" -- "$source_location" "$curr_backup_dir"; # | sed '/\/\.svn\//d; /^cd+++++++ .*\/$/d';
fi;
# Print a blank line between two backups.
let i++;
[ $i -eq $# ] || echo;
done;
)}
function diff-to-backup () {(
local backup_dir="$HOME/backups";
for x in "${@:-.}"; do
full_path="$(php -r 'echo realpath($_SERVER["argv"][1]);' "$x")";
# Check for previous backups.
local prev_backup='';
shopt -s nullglob;
for prev_backup in "$backup_dir/"*"$full_path"; do
:
done;
if [ -z "$prev_backup" ]; then
echo "There are no backups of \"$x\"";
exit 1;
else
udiff -x .svn -r "$prev_backup" "$x";
fi;
echo;
done;
)}
# Processes
# -----------------------------------------------------------------------------
# Show a one-line process tree of the given process, defaulting to the current
# shell. By specifying this as a function instead of a separate script, we
# avoid the extra shell process.
function process-tree {
pid="${1:-$$}";
orig_pid="$pid";
local commands=();
while [ "$pid" != "$ppid" ]; do
# Read the parent's process ID and the current process's command line.
{
read -d ' ' ppid;
read command;
} < <(ps c -p "$pid" -o ppid= -o command= | sed 's/^ *//');
# XXX This does not quite work yet with screen on OS x. Find out why.
# echo "PID: $pid // PPID: $ppid // CMD: $command" 1>&2;
# Stop when we have reached the first process, or an sshd/login process.
if [ -z "$ppid" -o "$ppid" -eq 0 -o "$ppid" -eq 1 -o "$command" = 'login' -o "$command" = 'sshd' ]; then
# Include screen/xterm as the "root" process.
if [ "$command" = 'screen' -o "$command" = 'xterm' ]; then
commands=("$command" "${commands[@]}");
fi;
break;
fi;
# Insert the command in the front of the process array.
commands=("$command" "${commands[@]}");
# Prepare for the next iteration.
pid="$ppid";
ppid=;
done;
# Hide the first bash process.
set -- "${commands[@]}";
if [ "$1" = '-bash' -o "$1" = 'bash' ]; then
shift;
commands=("$@");
fi;
# Print the tree with the specified separator.
separator='→';
output="$(IFS="$separator"; echo "${commands[*]}")";
echo "${output//$separator/ $separator }";
}
# Show the top 10 processes.
function top10 {
# Default columns displayed by "top" on Debian Linux and Mac OS X:
# 1 2 3 4 5 6 7 8 9 10 11 12
# Linux: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
# Darwin: PID COMMAND %CPU TIME #TH #WQ #PORTS #MREGS RPRVT RSHRD RSIZE VPRVT VSIZE PGRP PPID STATE UID FAULTS COW MSGSENT MSGRECV SYSBSD SYSMACH CSW PAGEINS USER
# 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
if [[ "$OSTYPE" =~ ^darwin ]]; then
# Mac OS X's top does not calculate the CPU usage when sampling only
# once. So, sample twice and only keep the output of the second
# sample. This makes it seem very slow, but them's the breaks.
local output="$(top -l 2 -n 10 -o CPU -stats PID,USER,CPU,VSIZE,RSIZE,RSHRD,STATE,TIME,COMMAND)";
output="$(tail -n "$(($(wc -l <<< "$output") / 2))" <<< "$output")";
else
# Debian's top (and possibly other Linux versions) does not allow
# requesting specific fields on the command line, so create a
# temporary .toprc somewhere and use that. The "fieldscur" below
# correspond to the "-stats" option for OS X's "top". See above.
local tmp_dir="$(mktemp -d -t "top10.$$.XXXX")";
cat > "$tmp_dir/.toprc" <<-EOD
RCfile for "top with windows" # shameless braggin'
Id:a, Mode_altscr=0, Mode_irixps=1, Delay_time=3.000, Curwin=0
Def fieldscur=AEKhiOQTWnMbcdfgjplrsuvyzX
winflags=62777, sortindx=10, maxtasks=0
summclr=1, msgsclr=1, headclr=3, taskclr=1
EOD
local output="$(HOME="$tmp_dir"; top -bn 1)";
fi;
# Output the result, and use "column" to align the process columns a bit
# better than "top" itself does. This does screw up the command names when
# they contain a space, e.g. "Chromium Helper" => "Chromium Helper".
local pid_start_line="$(egrep -nm1 '^\s*PID' <<< "$output" || echo 65536)";
pid_start_line="${pid_start_line%:*}";
head -n $(($pid_start_line - 1)) <<< "$output";
tail -n +$pid_start_line <<< "$output" | head -n 11 | column -t;
}
# Sort the "du" output and use human-readable units.
function duh {
du -sk "$@" | 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;
}
# Compare one or more URLs "before" and "after".
function diff-url () {(
cd /tmp || return $?;
declare -a urls;
declare -a before;
declare -a after;
# Remember all URLs.
for url; do
urls+=("$url");
done;
# Save all URLs to "before and after".
for curr in {before,after}; do
read -p "Press Enter to save $curr...";
for ((i = 0; i < ${#urls[@]}; i++)); do
url="${urls[$i]}";
num="$(printf '%02d' "$i")";
file="$curr-$num.html";
[ "$curr" = 'before' ] \
&& before+=("$file") \
|| after+=("$file");
wget -qO- "$url" | sed 's/m=[0-9]*//g; s/[0-9a-f]\{32\}//g; s/[0-9]* keer bekeken//' > "$file";
[ -z "$prev_x" ] && prev_x="$x";
done;
done;
# Loop through all URLs to diff their before and after.
for ((i = 0; i < ${#urls[@]}; i++)); do
url="${urls[$i]}";
num="$(printf '%02d' "$i")";
before="${before[$i]}";
after="${after[$i]}";
udiff --label="$url (before)" --label="$url (after)" "$before" "$after";
rm -f "$before" "$after";
done | colordiff | less -XFIRd;
)}
# Edit the files found with the previous "ack" command using Vim (or the
# default editor).
function vack {
local cmd='';
if [ $# -eq 0 ]; then
cmd="$(fc -nl -1)";
cmd="${cmd:2}";
else
cmd='ack';
for x; do
cmd="$cmd $(printf '%q' "$x")";
done;
echo "$cmd";
fi;
if [ "${cmd:0:4}" != 'ack ' ]; then
$cmd;
return $?;
fi;
declare -a files;
while read -r file; do
echo "$file";
files+=("$file");
done < <(bash -c "${cmd/ack/ack -l}");
"${EDITOR:-vim}" "${files[@]}";
}
# Convert the parameters or STDIN to lowercase.
function lc {
if [ $# -eq 0 ]; then
tr '[:upper:]' '[:lower:]';
else
tr '[:upper:]' '[:lower:]' <<< "$@";
fi;
}
# Convert the parameters or STDIN to uppercase.
function uc {
if [ $# -eq 0 ]; then
tr '[:lower:]' '[:upper:]';
else
tr '[:lower:]' '[:upper:]' <<< "$@";
fi;
}
# Use PHP's built-in support to encode and decode base64.
function base64 {
if [ $# -eq 0 ]; then
echo 'Usage: base64 [encode|decode] <string>';
return;
fi;
local action='decode';
if [ "$1" = 'decode' ]; then
action='decode';
shift;
elif [ "$1" = 'encode' ]; then
action='encode';
shift;
fi;
echo "$@" | php -r "echo base64_$action(file_get_contents('php://stdin'));";
echo;
}
# Highlight STDIN based on PCRE patterns.
function highlight {
local color=33;
local perl_regex='';
while [ $# -gt 0 ]; do
local brightness=1;
local param="$1";
if [ "${param:0:2}" = "--" ]; then
if [ "${param:2:5}" == "dark-" ]; then
brightness=0;
param="--${param:7}";
elif [ "${param:2:6}" == "light-" ]; then
brightness=1;
param="--${param:8}";
fi;
case "${param:2}" in
'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'pink' | 'cyan' | 'white')
param="--color=${param:2}";
;;
esac;
fi;
if [[ "${param:0:8}" = '--color=' ]]; then
case ${param:8} in
'black')
color=30;;
'red')
color=31;;
'green')
color=32;;
'yellow')
color=33;;
'blue')
color=34;;
'magenta' | 'pink')
color=35;;
'cyan')
color=36;;
'white')
color=37;;
*)
echo default;;
esac
shift;
fi
perl_regex="$perl_regex;s@${1//@/\\@/}@$(echo -n $'\e['$brightness';'$color'm$&'$'\e[m')@g";
shift;
done;
perl -p -e "select(STDOUT); $| = 1; ${perl_regex:1}";
}
# 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.
function wtfis {
local cmd type i=1 ret=0;
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="$(type "$cmd")";
ret=$?;
if [ $ret -eq 0 ]; then
# Try to get the physical path. This works for hashes and
# "normal" binaries.
local path="$(type -p "$cmd")";
if [ -z "$path" ]; then
# Show the output from "type" without ANSI escapes.
echo "${type//$'\e'/\\033}";
case "$(type -t "$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.
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.)
man "$(basename "$path")" 2>/dev/null | col -b | \
awk '/^NAME$/,/^$/' | {
local buf line;
read -r line;
while read -r line; do
buf="$buf${line/. */.} ";
if [[ "$buf" =~ \.\ $ ]]; then
echo "$buf";
break;
fi;
done;
[ -n "$buf" ] && echo "$buf";
}
# Then, combine the output "type" and "file".
local fileinfo="$(file "$path")";
echo "${type}${fileinfo/$path}";
# Finally, show it using "ls" and highlight the path.
local ls="$(command ls -dalF "$path")";
echo "${ls/$path/$'\e[7m'${path}$'\e[27m'}";
fi;
fi;
# Separate the output for all but the last command with blank lines.
[ $i -lt $# ] && echo;
let i++;
done;
return $ret;
}
complete -A command wtfis;
# 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'.
#
# Examples of input and output:
#
# $ 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
#
# When requesting a different timezone like in the last example, make sure to
# execute the command in a subshell to avoid changing your timezone for the
# rest of the session.
#
# For more info, check out http://kak.be/gnudateformats.
function whenis {
local error='Unable to parse that using http://kak.be/gnudateformats';
# 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="$*";
[[ "$date" =~ ^[[:space:]]*$ ]] && date='now';
if [[ "$date" =~ ^[0-9]+$ ]] || [[ "$OSTYPE" =~ ^darwin ]]; then
# Use PHP for UNIX timestamps and on OS X, where "date" is not GNU's.
php -r '
error_reporting(-1);
$format = $_SERVER["argv"][1];
$date = $_SERVER["argv"][2];
if (!is_numeric($date)) {
$date = strtotime($date);
if ($date === false) {
fputs(STDERR, $_SERVER["argv"][3] . PHP_EOL);
exit(1);
}
}
echo strftime($format, $date), PHP_EOL;
' -- "$format" "$date" "$error";
else
# Use GNU date in all other situations.
date -d "$date" +"$format";
fi;
}
# Start your editor ($EDITOR, defaulting to "vim") on the last file specified.
# This is useful to quickly view the last in a series of timestamped files,
# e.g.:
# $ ls -1 *.sql
# 20111021-112318.sql
# 20111021-112328.sql
# 20111021-112403.sql
# 20111021-112500.sql
# 20111021-112704.sql
# 20111021-112724.sql
# 20111021-112729.sql
# 20111021-113949.sql
# $ vilast *.sql # will edit 20111021-113949.sql
function vilast {
(($#)) && ${EDITOR:-vim} "${!#}";
}
# A quick way to invoke a read-only Vim on the last file. See "vilast".
function viewlast {
(EDITOR=view vilast "$@");
}
#
# Start a PHP server from a directory, optionally specifying the port
# (Requires PHP 5.4.0+.)
function phpserver() {
local port="${1:-4000}";
local ip=$(ipconfig getifaddr en1);
sleep 1 && open "http://${ip}:${port}/" &
php -S "${ip}:${port}";
}
# Compare original and gzipped file size
function gz() {
local origsize=$(wc -c < "$1");
local gzipsize=$(gzip -c "$1" | wc -c);
local ratio=$(echo "$gzipsize * 100 / $origsize" | bc -l);
printf "orig: %d bytes\n" "$origsize";
printf "gzip: %d bytes (%2.2f%%)\n" "$gzipsize" "$ratio";
}
# Syntax-highlight JSON strings or files
# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json`
function json() {
if [ -t 0 ]; then # argument
python -mjson.tool <<< "$*" | pygmentize -l javascript;
else # pipe
python -mjson.tool | pygmentize -l javascript;
fi;
}
# Run `dig` and display the most useful info
function digga() {
dig +nocmd "$1" any +multiline +noall +answer;
}
# UTF-8-encode a string of Unicode symbols
function escape() {
printf "\\\x%s" $(printf "$@" | xxd -p -c1 -u);
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
# Decode \x{ABCD}-style Unicode escape sequences
function unidecode() {
perl -e "binmode(STDOUT, ':utf8'); print \"$@\"";
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
# Get a character’s Unicode code point
function codepoint() {
perl -e "use utf8; print sprintf('U+%04X', ord(\"$@\"))";
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
# Show all the names (CNs and SANs) listed in the SSL certificate
# for a given domain
function getcertnames() {
if [ -z "${1}" ]; then
echo "ERROR: No domain specified.";
return 1;
fi;
local domain="${1}";
echo "Testing ${domain}…";
echo ""; # newline
local tmp=$(echo -e "GET / HTTP/1.0\nEOT" \
| openssl s_client -connect "${domain}:443" -servername "${domain}" 2>&1);
if [[ "${tmp}" = *"-----BEGIN CERTIFICATE-----"* ]]; then
local certText=$(echo "${tmp}" \
| openssl x509 -text -certopt "no_aux, no_header, no_issuer, no_pubkey, \
no_serial, no_sigdump, no_signame, no_validity, no_version");
echo "Common Name:";
echo ""; # newline
echo "${certText}" | grep "Subject:" | sed -e "s/^.*CN=//" | sed -e "s/\/emailAddress=.*//";
echo ""; # newline
echo "Subject Alternative Name(s):";
echo ""; # newline
echo "${certText}" | grep -A 1 "Subject Alternative Name:" \
| sed -e "2s/DNS://g" -e "s/ //g" | tr "," "\n" | tail -n +2;
return 0;
else
text=$(cat) # pipe
fi
echo "ERROR: Certificate not found.";
return 1;
}
# `s` with no arguments opens the current directory in Sublime Text, otherwise
# opens the given location
function s() {
if [ $# -eq 0 ]; then
subl .;
else
subl "$@";
fi;
}
# `a` with no arguments opens the current directory in Atom Editor, otherwise
# opens the given location
function a() {
if [ $# -eq 0 ]; then
atom .;
else
atom "$@";
fi;
}
# `v` with no arguments opens the current directory in Vim, otherwise opens the
# given location
function v() {
if [ $# -eq 0 ]; then
vim .;
else
vim "$@";
fi;
}
# `o` with no arguments opens the current directory, otherwise opens the given
# location
function o() {
if [ $# -eq 0 ]; then
open .;
else
open "$@";
fi;
}
# `tre` is a shorthand for `tree` with hidden files and color enabled, ignoring
# the `.git` directory, listing directories first. The output gets piped into
# `less` with options to preserve color and line numbers, unless the output is
# small enough for one screen.
function tre() {
tree -aC -I '.git|node_modules|bower_components' --dirsfirst "$@" | less -FRNX;
}
# Manually remove a downloaded app or file from the quarantine
function unquarantine() {
for attribute in com.apple.metadata:kMDItemDownloadedDate com.apple.metadata:kMDItemWhereFroms com.apple.quarantine; do
xattr -r -d "$attribute" "$@"
done
}
function flushdns() {
sudo launchctl unload /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
echo -n "mDNS unloading..."
sleep 5
echo " [done]"
sudo launchctl load /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
echo -n "mDNS loading....."
sleep 5
echo " [done]"
}
function jhome() {
export JAVA_HOME=`/usr/libexec/java_home $@`
echo "JAVA_HOME:" $JAVA_HOME
echo "java -version:"
java -version
}