more robust initialization, remove old func
[distro-setup] / brc
1 #!/bin/bash
2 # this gets sourced. shebang is just for file mode detection
3
4 # note, to catch errors in functions but not outside, do:
5 # set -E -o pipefail
6 # trap return ERR
7 # trap 'trap ERR' RETURN
8
9
10
11 ############
12 # settings #
13 ############
14
15 CDPATH=.
16
17 set -o pipefail
18
19 # remove all aliases. aliases provided by the system tend to get in the way,
20 # for example, error happens if I try to define a function the same name as an alias
21 unalias -a
22
23 # remove gnome keyring warning messages
24 # there is probably a more proper way, but I didn't find any easily on google
25 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
26 #unset GNOME_KEYRING_CONTROL
27
28 # use extra globing features.
29 shopt -s extglob
30 # include .files when globbing, but ignore files name . and ..
31 # setting this also sets dotglob.
32 # Note, this doesn't work in bash 4.4 anymore, for paths with
33 # more than 1 directory, like a/b/.foo, since * is fixed to not match /
34 export GLOBIGNORE=*/.:*/..
35
36 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
37 # still broken in wheezy
38 # still buggered in latest stable from the web, version 2.1
39 # perhaps its fixed in newer git version, which fails to make for me
40 # this note is from 6-2014.
41 # Also, enabling this before sourcing .bashrc makes PATH be empty.
42 #shopt -s nullglob
43
44 # make tab on an empty line do nothing
45 shopt -s no_empty_cmd_completion
46
47 # advanced completion
48 # http://bash-completion.alioth.debian.org/
49 # might be sourced by the system already, but I've noticed it not being sourced before
50 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
51 . /usr/share/bash-completion/bash_completion
52 fi
53
54
55 # fix spelling errors for cd, only in interactive shell
56 shopt -s cdspell
57 # append history instead of overwritting it
58 shopt -s histappend
59 # for compatibility, per gentoo/debian bashrc
60 shopt -s checkwinsize
61 # attempt to save multiline single commands as single history entries.
62 shopt -s cmdhist
63 # enable **
64 shopt -s globstar
65
66
67 # inside emcas fixes
68 if [[ $RLC_INSIDE_EMACS ]]; then
69 # EMACS is used by bash on startup, but we don't need it anymore.
70 # plus I hit a bug in a makefile which inherited it
71 unset EMACS
72 export RLC_INSIDE_EMACS
73 export PAGER=cat
74 export MANPAGER=cat
75 # scp completion does not work, but this doesn't fix it. todo, figure this out
76 complete -r scp &> /dev/null
77 # todo, remote file completion fails, figure out how to turn it off
78 export NODE_DISABLE_COLORS=1
79 # This get's rid of ugly terminal escape chars in node repl
80 # sometime, I'd like to have completion working in emacs shell for node
81 # the offending chars can be found in lib/readline.js,
82 # things that do like:
83 # stream.write('\x1b[' + (x + 1) + 'G');
84 # We can remove them and keep readline, for example by doing this
85 # to start a repl:
86 #!/usr/bin/env nodejs
87 # var readline = require('readline');
88 # readline.cursorTo = function(a,b,c) {};
89 # readline.clearScreenDown = function(a) {};
90 # const repl = require('repl');
91 # var replServer = repl.start('');
92 #
93 # no prompt, or else readline complete seems to be confused, based
94 # on our column being different? node probably needs to send
95 # different kind of escape sequence that is not ugly. Anyways,
96 # completion doesn't work yet even with the ugly prompt, so whatever
97 #
98 export NODE_NO_READLINE=1
99
100 fi
101
102
103 if [[ $- == *i* ]]; then
104 # for readline-complete.el
105 if [[ $RLC_INSIDE_EMACS ]]; then
106 # all for readline-complete.el
107 stty echo
108 bind 'set horizontal-scroll-mode on'
109 bind 'set print-completions-horizontally on'
110 bind '"\C-i": self-insert'
111 else
112 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
113 if [[ $TERM == "xterm" ]]; then
114 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
115 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
116 else
117 bind '"\eOc": shell-forward-word'
118 bind '"\eOd": shell-backward-word'
119 fi
120 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
121 # gnome-terminal, overridden by bash, or disabled by the system
122 stty werase undef lnext undef stop undef start undef
123
124 fi
125
126 fi
127
128
129 # history number. History expansion is good.
130 PS4='$LINENO+ '
131 # history file size limit, set to unlimited.
132 # this needs to be different from the default because
133 # default HISTFILESIZE is 500 and could clobber our history
134 HISTFILESIZE=
135 # max commands 1 session can append/read from history
136 HISTSIZE=100000
137 # my own history size limit based on lines
138 HISTFILELINES=1000000
139 HISTFILE=$HOME/.bh
140 # the time format display when doing the history command
141 # also, setting this makes the history file record time
142 # of each command as seconds from the epoch
143 HISTTIMEFORMAT="%I:%M %p %m/%d "
144 # consecutive duplicate lines don't go in history
145 HISTCONTROL=ignoredups
146 # works in addition to HISTCONTROL to do more flexible things
147 # it could also do the same things as HISTCONTROL and thus replace it,
148 # but meh. dunno why, but just " *" does glob expansion, so use [ ] to avoid it.
149 HISTIGNORE='k *:[ ]*'
150
151 export BC_LINE_LENGTH=0
152
153
154 # note, if I use a machine I don't want files readable by all users, set
155 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
156
157 C_DEFAULT_DIR=/a
158
159
160 ###################
161 ## include files ###
162 ###################
163 for _x in /a/bin/distro-functions/src/* /a/bin/!(githtml)/*-function?(s); do
164 source "$_x"
165 done
166 unset _x
167 # so I can share my bashrc
168 for x in /a/bin/bash_unpublished/source-!(.#*); do source $x; done
169 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
170 source /a/bin/log-quiet/logq-function
171 path_add /a/exe
172 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
173 # based on readme.debian. dunno if this will break on other distros.
174 _x=/usr/share/wcd/wcd-include.sh
175 if [[ -e $_x ]]; then source $_x; fi
176
177
178 ###############
179 ### aliases ###
180 ###############
181
182 # very few aliases, functions are always preferred.
183
184 # ancient stuff.
185 if [[ $OS == Windows_NT ]]; then
186 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
187 export DISPLAY=nt
188 alias j='command cygpath'
189 alias t='command cygstart'
190 alias cygstart='echo be quick, use the alias "t" instead :\)'
191 alias cygpath='echo be quick, use the alias "j" instead :\)'
192 fi
193
194
195
196 # keep this in mind? good for safety.
197 # alias cp='cp -i'
198 # alias mv='mv -i'
199
200
201 # remove any default aliases for these
202 unalias ls ll grep &>/dev/null ||:
203
204
205
206
207
208
209
210
211
212 #####################
213 ### functions ####
214 #####################
215
216
217 ..() { c ..; }
218 ...() { c ../..; }
219 ....() { c ../../..; }
220 .....() { c ../../../..; }
221 ......() { c ../../../../..; }
222
223
224 # file cut copy and paste, like the text buffers :)
225 # I havn't tested these.
226 _fbufferinit() { # internal use by
227 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
228 rm -rf "$my_f_tempdir"/*
229 }
230 fcp() { # file cp
231 _fbufferinit
232 cp "$@" "$my_f_tempdir"/
233 }
234 fct() { # file cut
235 _fbufferinit
236 mv "$@" "$my_f_tempdir"/
237 }
238 fpst() { # file paste
239 [[ $2 ]] && { echo too many arguments; return 1; }
240 target=${1:-.}
241 cp "$my_f_tempdir"/* "$target"
242 }
243
244
245 # todo, update this
246 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
247
248
249 _cdiff-prep() {
250 # join options which are continued to multiples lines onto one line
251 local first=true
252 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
253 # remove leading spaces/tabs. assumes extglob
254 if [[ $line == "[ ]*" ]]; then
255 line="${line##+( )}"
256 fi
257 if $first; then
258 pastline="$line"
259 first=false
260 elif [[ $line == *=* ]]; then
261 echo "$pastline" >> "$2"
262 pastline="$line"
263 else
264 pastline="$pastline $line"
265 fi
266 done
267 echo "$pastline" >> "$2"
268 }
269
270 _khfix_common() {
271 local h=${1##*@}
272 ssh-keygen -R $h -f $(readlink -f ~/.ssh/known_hosts)
273 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
274 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
275 }
276 khfix() { # known hosts fix
277 _khfix_common "$@"
278 ssh $1 :
279 }
280 khcopy() {
281 _khfix_common "$@"
282 ssh-copy-id $1
283 }
284
285 a() {
286 beet "${@}"
287 }
288
289 ack() { ack-grep "$@"; }
290
291 astudio() {
292 # googling android emulator libGL error: failed to load driver: r600
293 # lead to http://stackoverflow.com/a/36625175/14456
294 export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1
295 /a/opt/android-studio/bin/studio.sh "$@" &r;
296 }
297
298 b() {
299 # backwards
300 c -
301 }
302
303 bkrun() {
304 # use -p from interactive shell
305 btrbk-run -p "$@"
306 }
307
308 bfg() { java -jar /a/opt/bfg-1.12.14.jar "$@"; }
309
310 btc() {
311 local f=/etc/bitcoin/bitcoin.conf
312 bitcoin-cli -$(s grep rpcuser= $f) -$(s grep rpcpassword= $f) "$@"
313 }
314
315 btcusd() {
316 local price
317 price="$(curl -s https://blockchain.info/ticker | jq .USD.last)"
318 printf "$%s\n" "$price"
319 if [[ $1 ]]; then
320 printf "$%.2f\n" "$(echo "scale=2; $price * $1"| bc -l)"
321 fi
322 }
323
324 # c. better cd
325 if [[ $RLC_INSIDE_EMACS ]]; then
326 c() { wcd -c -z 50 -o "$@"; }
327 else
328 # lets see what the fancy terminal does from time to time
329 c() { wcd -c -z 50 "$@"; }
330 fi
331
332 caa() { git commit --amend --no-edit -a; }
333
334 calc() { echo "scale=3; $*" | bc -l; }
335 # no having to type quotes, but also no command history:
336 clc() {
337 local x
338 read -r x
339 echo "scale=3; $x" | bc -l
340 }
341
342 cam() {
343 git commit -am "$*"
344 }
345
346 ccat () { # config cat. see a config without extra lines.
347 grep '^\s*[^[:space:]#]' "$@"
348 }
349
350 cdiff() {
351 # diff config files,
352 # setup for format of postfix, eg:
353 # option = stuff[,]
354 # [more stuff]
355 local pastline
356 local unified="$(mktemp)"
357 local f1="$(mktemp)"
358 local f2="$(mktemp)"
359 _cdiff-prep "$1" "$f1"
360 _cdiff-prep "$2" "$f2"
361 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
362 while IFS= read -r line; do
363 # the default bright red / blue doesn't work in emacs shell
364 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
365 done < "$unified"
366 }
367
368 cgpl()
369 {
370 if (($#)); then
371 cp /a/bin/data/COPYING "$@"
372 else
373 cp /a/bin/data/COPYING .
374 fi
375 }
376 capache()
377 {
378 if (($#)); then
379 cp /a/bin/data/LICENSE "$@"
380 else
381 cp /a/bin/data/LICENSE .
382 fi
383 }
384 chown() {
385 # makes it so chown -R symlink affects the symlink and its target.
386 if [[ $1 == -R ]]; then
387 shift
388 command chown -h "$@"
389 command chown -R "$@"
390 else
391 command chown "$@"
392 fi
393 }
394
395 cim() {
396 git commit -m "$*"
397 }
398
399 cl() {
400 # choose recent directory. cl = cd list
401 c =
402 }
403
404 d() { builtin bg; }
405 complete -A stopped -P '"%' -S '"' d
406
407 dat() { # do all tee, for more complex scripts
408 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
409 }
410 da() { # do all
411 local host
412 "$@"
413 for host in x2 tp treetowl; do
414 ssh $host "$@"
415 done
416 }
417
418 dc() {
419 diff --strip-trailing-cr -w "$@" # diff content
420 }
421
422 debian_pick_mirror () {
423 # netselect-apt finds a fast mirror.
424 # but we need to replace the mirrors ourselves,
425 # because it doesn't do that. best it can do is
426 # output a basic sources file
427 # here we get the server it found, get the main server we use
428 # then substitute all instances of one for the other in the sources file
429 # and backup original to /etc/apt/sources.list-original.
430 # this is idempotent. the only way to identify debian sources is to
431 # note the original server, so we put it in a comment so we can
432 # identify it later.
433 local file=$(mktemp -d)/f # safe way to get file name without creating one
434 sudo netselect-apt -o "$file" || return 1
435 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
436 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
437 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
438 sudo apt-get update
439 }
440
441 despace() {
442 local x y
443 for x in "$@"; do
444 y="${x// /_}"
445 safe_rename "$x" "$y"
446 done
447 }
448
449 dt() {
450 date "+%A, %B %d, %r" "$@"
451 }
452
453 dus() {
454 du -sh ${@:-*} | sort -h
455 }
456
457
458
459 e() { echo "$@"; }
460
461
462 ediff() {
463 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
464 emacs --eval "(ediff-files \"$1\" \"$2\")"
465 }
466
467
468 envload() { # load environment from a previous: export > file
469 local file=${1:-$HOME/.${USER}_env}
470 eval "$(export | sed 's/^declare -x/export -n/')"
471 while IFS= read -r line; do
472 # declare -x makes variables local to a function
473 eval ${line/#declare -x/export}
474 done < "$file"
475 }
476
477 f() {
478 # cd forward
479 c +
480 }
481
482 fa() {
483 # find array. make an array of file names found by find into $x
484 # argument: find arguments
485 # return: find results in an array $x
486 while read -rd ''; do
487 x+=("$REPLY");
488 done < <(find "$@" -print0);
489 }
490
491 faf() { # find all files
492 find $@ -type f
493 }
494
495 fastboot() { /a/opt/androidsdk/platform-tools/fastboot "$@"; }
496
497 ff() {
498 if type -P firefox &>/dev/null; then
499 firefox "$@"
500 else
501 iceweasel "$@"
502 fi
503 }
504
505
506
507 fn() {
508 firefox -P alt "$@" >/dev/null 2>&1
509 }
510
511
512 fsdiff () {
513 local missing=false
514 local dname="${PWD##*/}"
515 local m="/a/tmp/$dname-missing"
516 local d="/a/tmp/$dname-diff"
517 [[ -e $d ]] && rm "$d"
518 [[ -e $m ]] && rm "$m"
519 local msize=0
520 local fsfile
521 while read -r line; do
522 fsfile="$1${line#.}"
523 if [[ -e "$fsfile" ]]; then
524 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
525 else
526 missing=true
527 echo "$line" >> "$m"
528 msize=$((msize + 1))
529 fi
530 done < <(find -type f )
531 if $missing; then
532 echo "$m"
533 (( msize <= 100 )) && cat $m
534 fi
535 }
536 fsdiff-test() {
537 # expected output, with different tmp dirs
538 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
539 # /a/tmp/tmp.qLDkYxBYPM-missing
540 # ./b
541 cd $(mktemp -d)
542 echo ok > a
543 echo nok > b
544 mkdir c
545 echo ok > c/d
546 local x=$(mktemp -d)
547 mkdir $x/c
548 echo different > $x/c/d
549 echo ok > $x/a
550 fsdiff $x
551 }
552 rename-test() {
553 # test whether missing files were renamed, generally for use with fsdiff
554 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
555 # echos non-renamed files
556 local x y found
557 unset sums
558 for x in "$2"/*; do
559 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
560 done
561 while read -r line; do
562 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
563 renamed=false
564 for x in "${sums[@]}"; do
565 if [[ $missing_sum == "$x" ]]; then
566 renamed=true
567 break
568 fi
569 done
570 $renamed || echo "$line"
571 done < "$1"
572 return 0
573 }
574
575 feh() {
576 # F = fullscren, z = random, Z = auto zoom
577 command feh -FzZ "$@"
578 }
579
580 funce() {
581 # like -e for functions. returns on error.
582 # at the end of the function, disable with:
583 # trap ERR
584 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
585 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
586 trap ERR
587 return' ERR
588 }
589
590
591 fw() {
592 firefox -P default "$@" >/dev/null 2>&1
593 }
594
595 getdir () {
596 local help="Usage: getdir [--help] PATH
597 Output the directory of PATH, or just PATH if it is a directory."
598 if [[ $1 == --help ]]; then
599 echo "$help"
600 return 0
601 fi
602 if [[ $# -ne 1 ]]; then
603 echo "getdir error: expected 1 argument, got $#"
604 return 1
605 fi
606 if [[ -d $1 ]]; then
607 echo "$1"
608 else
609 local dir="$(dirname "$1")"
610 if [[ -d $dir ]]; then
611 echo "$dir"
612 else
613 echo "getdir error: directory does not exist"
614 return 1
615 fi
616 fi
617 }
618
619 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
620 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
621 local gitroot
622 gitroot || return 1 # function to set gitroot
623 builtin cd "$gitroot"
624 git symbolic-ref HEAD refs/heads/$1
625 rm .git/index
626 git clean -fdx
627 }
628
629 gitroot() {
630 local help="Usage: gitroot [--help]
631 Print the full path to the root of the current git repo
632
633 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
634 and works in older versions of git which did not have that."
635 if [[ $1 == --help ]]; then
636 echo "$help"
637 return
638 fi
639 local p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
640 [[ $p != /* ]] && p=$PWD
641 echo "${p%%/.git}"
642 }
643
644 gmacs() {
645 # quit will prompt if the program crashes.
646 gdb -ex=r -ex=quit --args emacs "$@"; r;
647 }
648
649 gdkill() {
650 # kill the emacs daemon
651 pk1 emacs --daemon
652 }
653
654 gse() {
655 git send-email --notes '--envelope-sender=<ian@iankelling.org>' \
656 --suppress-cc=self "$@"
657 }
658
659 gr() {
660 grep -iIP --color=auto "$@"
661 }
662
663 grr() {
664 if [[ ${#@} == 1 ]]; then
665 grep -riIP --color=auto "$@" .
666 else
667 grep -riIP --color=auto "$@"
668 fi
669 }
670
671 hstatus() {
672 # do git status on published repos
673 cd /a/bin/githtml
674 for x in !(forks) forks/* ian-specific/*; do
675 cd `readlink -f $x`/..
676 hr
677 echo $x
678 i status
679 cd /a/bin/githtml
680 done
681 }
682
683 hl() { # history limit. Write extra history to archive file.
684 # todo: this is not working or not used currently
685 local max_lines linecount tempfile prune_lines x
686 local harchive="${HISTFILE}_archive"
687 for x in "$HISTFILE" "$harchive"; do
688 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
689 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
690 echo "error in hl: history file \$x:$x no good"
691 return 1
692 fi
693 done
694 history -a # save history
695 max_lines=$HISTFILELINES
696 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
697 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
698 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
699 if (($linecount > $max_lines)); then
700 prune_lines=$(($linecount - $max_lines))
701 head -n $prune_lines "$HISTFILE" >> "$harchive" \
702 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
703 fi
704 }
705
706 hr() { # horizontal row. used to break up output
707 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS)
708 echo
709 }
710
711 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
712
713
714 i() { git "$@"; }
715 # modified from ~/local/bin/git-completion.bash
716 # other completion commands are mostly taken from bash_completion package
717 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
718 || complete -o default -o nospace -F _git i
719
720 if ! type service &>/dev/null; then
721 service() {
722 echo actually running: systemctl $2 $1
723 systemctl $2 $1
724 }
725 fi
726
727 ic() {
728 # fast commit all
729 git commit -am "$*"
730 }
731
732 idea() {
733 /a/opt/idea-IC-163.7743.44/bin/idea.sh "$@" &r
734 }
735
736 ifn() {
737 # insensitive find
738 find -L . -not \( -name .svn -prune -o -name .git -prune \
739 -o -name .hg -prune \) -iname "*$**" 2>/dev/null
740 }
741
742
743 if [[ $OS == Windows_NT ]]; then
744 # cygstart wrapper
745 cs() {
746 cygstart "$@" &
747 }
748 xp() {
749 explorer.exe .
750 }
751 # launch
752 o() {
753 local x=(*$1*)
754 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
755 cygstart *$1* &
756 }
757 else
758 o() {
759 if type gvfs-open &> /dev/null ; then
760 gvfs-open "$@"
761 else
762 xdg-open "$@"
763 fi
764 # another alternative is run-mailcap
765 }
766 fi
767
768
769
770 istext() {
771 grep -Il "" "$@" &>/dev/null
772 }
773
774 jtail() {
775 journalctl -n 10000 -f "$@" | grep -Evi "^(\S+\s+){4}(sudo|sshd|cron)"
776 }
777
778
779 l() {
780 if [[ $PWD == /[iap] ]]; then
781 command ls -A --color=auto -I lost+found "$@"
782 else
783 command ls -A --color=auto "$@"
784 fi
785 }
786
787
788 lcn() { locate -i "*$**"; }
789
790 lld() { ll -d "$@"; }
791
792 low() { # make filenames all lowercase
793 local x y
794 for x in "$@"; do
795 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
796 [[ $y != $x ]] && mv "$x" "$y"
797 done
798 }
799
800
801
802
803 lower() { # make first letter of filenames lowercase.
804 local x
805 for x in "$@"; do
806 if [[ ${x::1} == [A-Z] ]]; then
807 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
808 safe_rename "$x" "$y"
809 fi
810 done
811 }
812
813
814 k() { # history search
815 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40;
816 }
817
818
819 make-targets() {
820 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
821 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
822 }
823
824
825 mkc() {
826 mkdir "$1"
827 c "$1"
828 }
829
830 mkdir() { command mkdir -p "$@"; }
831
832 pithos() {
833 cd /
834 export PYTHONPATH=/a/opt/Pithosfly
835 python3 -m pithos&r
836 }
837
838 pakaraoke() {
839 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
840 pactl load-module module-ladspa-sink sink_name=Karaoke master=alsa_output.usb-Audioengine_Audioengine_D1-00.analog-stereo plugin=karaoke_1409 label=karaoke control=-30
841 }
842
843
844 pfind() { #find *$1* in $PATH
845 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
846 local pathArray
847 IFS=: pathArray=($PATH); unset IFS
848 find "${pathArray[@]}" -iname "*$1*"
849 }
850
851 pk1() {
852 local pid
853 pid=($(pgrep -f "$*"))
854 case ${#pid[@]} in
855 1)
856 ps -F $pid
857 m kill $pid
858 ;;
859 0) echo "no pid found" ;;
860 *)
861 ps -F ${pid[@]}
862 ;;
863 esac
864 }
865
866 pick-trash() {
867 # trash-restore lists everything that has been trashed at or below CWD
868 # This picks out files just in CWD, not subdirectories,
869 # which also match grep $1, usually use $1 for a time string
870 # which you get from running restore-trash once first
871 local name x ask
872 local nth=1
873 # last condition is to not ask again for ones we skipped
874 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
875 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
876 name="$(echo "$name" | head -n $nth | tail -n 1 )"
877 read -p "$name [Y/n] " ask
878 if [[ ! $ask || $ask == [Yy] ]]; then
879 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
880 echo $x | restore-trash > /dev/null
881 elif [[ $ask == [Nn] ]]; then
882 nth=$((nth+1))
883 else
884 return
885 fi
886 done
887 }
888
889 postconfin() {
890 local MAPFILE
891 mapfile -t
892 local s
893 [[ $EUID == 0 ]] || s=s
894 $s postconf -ev "${MAPFILE[@]}"
895 }
896
897 pub() {
898 rld /a/h/_site/ li:/var/www/iankelling.org/html
899 }
900
901 pubip() { curl -4s https://icanhazip.com; }
902 whatismyip() { pubip; }
903
904
905 pwgen() {
906 # -m = min length
907 # -x = max length
908 # -t = print pronunciation
909 apg -m 12 -x 16 -t
910 }
911
912
913 q() { # start / launch a program in the backround and redir output to null
914 "$@" &> /dev/null &
915 }
916
917 r() {
918 exit "$@" 2>/dev/null
919 }
920
921 rbpipe() { rbt post -o --diff-filename=- "$@"; }
922 rbp() { rbt post -o "$@"; }
923
924 rl() {
925 # rsync, root is required to keep permissions right.
926 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
927 # --no-times --delete
928 # basically, make an exact copy, use checksums instead of file times to be more accurate
929 rsync -ahvic --delete "$@"
930 }
931 rld() {
932 # like rlu, but don't delete files on the target end which
933 # do not exist on the original end.
934 rsync -ahvic "$@"
935 }
936 complete -F _rsync -o nospace rld rl rlt
937
938 rlt() {
939 # rl without preserving modification time.
940 rsync -ahvic --delete --no-t "$@"
941 }
942
943 rlu() { # [OPTS] HOST PATH
944 # eg. rlu -opts frodo /testpath
945 # relative paths will expanded with readlink -f.
946 # useful for selectively sending dirs which have been synced with unison,
947 # where the path is the same on both hosts.
948 opts=("${@:1:$#-2}") # 1 to last -2
949 path="${@:$#}" # last
950 host="${@:$#-1:1}" # last -1
951 if [[ $path == .* ]]; then
952 path=$(readlink -f $path)
953 fi
954 # rync here uses checksum instead of time so we don't mess with
955 # unison relying on time as much. g is for group, same reason
956 # to keep up with unison.
957 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
958 }
959
960
961 rspicy() { # usage: HOST DOMAIN
962 # connect to spice vm remote host. use vspicy for local host
963 local port=$(ssh $1<<EOF
964 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
965 sed -rn "s/.*port='([0-9]+).*/\1/p"
966 EOF
967 )
968 if [[ $port ]]; then
969 spicy -h $1 -p $port
970 else
971 echo "error: no port found. check that the domain is running."
972 fi
973 }
974
975 s() {
976 # background
977 # I use a function because otherwise we can't use in a script,
978 # can't assign to variable.
979 #
980 # note: gksudo is recommended for X apps because it does not set the
981 # home directory to the same, and thus apps writing to ~ fuck things up
982 # with root owned files.
983 #
984 if [[ $EUID != 0 || $1 == -* ]]; then
985 SUDOD="$PWD" sudo -i "$@"
986 else
987 "$@"
988 fi
989 }
990
991 safe_rename() {
992 if [[ $# != 2 ]]; then
993 echo safe_rename error: $# args, need 2 >2
994 return 1
995 elif [[ $1 != $2 ]]; then
996 if [[ -e $2 ]]; then
997 echo Cannot rename "$1" to "$2" as it already exists.
998 else
999 mv "$1" "$2"
1000 fi
1001 fi
1002 }
1003
1004
1005 sb() { # sudo bash -c
1006 # use sb instead of s is for sudo redirections,
1007 # eg. sb 'echo "ok fine" > /etc/file'
1008 local SUDOD="$PWD"
1009 sudo -i bash -c "$@"
1010 }
1011 complete -F _root_command s sb
1012
1013 scssl() {
1014 # s gem install scss-lint
1015 pushd /a/opt/thoughtbot-guides
1016 git pull --stat
1017 popd
1018 scss-lint -c /a/opt/thoughtbot-guides/style/sass/.scss-lint.yml "$@"
1019 }
1020
1021 ser() {
1022 local s; [[ $EUID != 0 ]] && s=sudo
1023 if type -p systemctl &>/dev/null; then
1024 $s systemctl $1 $2
1025 else
1026 $s service $2 $1
1027 fi
1028 }
1029
1030 sgo() { # service go
1031 service=$1
1032 ser restart $service
1033 if type -p systemctl &>/dev/null; then
1034 ser enable $service
1035 fi
1036 }
1037
1038
1039 shellck() {
1040 # 2086 = unquoted $var
1041 # 2046 = unquoted $(cmd)
1042 # i had -x as an arg, but debian testing(stretch) doesn't support it
1043 shellcheck -e 2086,2046,2068,2006,2119 "$@"
1044 }
1045
1046
1047 slog() {
1048 # log with script. timing is $1.t and script is $1.s
1049 # -l to save to ~/typescripts/
1050 # -t to add a timestamp to the filenames
1051 local logdir do_stamp arg_base
1052 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1053 logdir="/a/dt/"
1054 do_stamp=false
1055 while getopts "lt" option
1056 do
1057 case $option in
1058 l ) arg_base=$logdir ;;
1059 t ) do_stamp=true ;;
1060 esac
1061 done
1062 shift $(($OPTIND - 1))
1063 arg_base+=$1
1064 [[ -e $logdir ]] || mkdir -p $logdir
1065 $do_stamp && arg_base+=$(date +%F.%T%z)
1066 script -t $arg_base.s 2> $arg_base.t
1067 }
1068 splay() { # script replay
1069 #logRoot="$HOME/typescripts/"
1070 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1071 scriptreplay "$1.t" "$1.s"
1072 }
1073
1074 sr() {
1075 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1076 if [[ $# == 0 ]]; then
1077 sudo -E bash -c -l "$(history -p '!!')"
1078 else
1079 echo this command redos last history item. no argument is accepted
1080 fi
1081 }
1082
1083 srm () {
1084 # with -ll, less secure but faster.
1085 command srm -ll "$@"
1086 }
1087
1088 srun() {
1089 scp $2 $1:/tmp
1090 ssh $1 /tmp/${2##*/} "${@:2}"
1091 }
1092
1093 swap() {
1094 local tmp
1095 tmp=$(mktemp)
1096 mv $1 $tmp
1097 mv $2 $1
1098 mv $tmp $2
1099 }
1100
1101 t() {
1102 local x
1103 local -a args
1104 if type -t trash-put >/dev/null; then
1105 # skip args that don't exist, or else trash-put will have an error
1106 for x in "$@"; do
1107 if [[ -e $x || -L $x ]]; then
1108 args+=("$x")
1109 fi
1110 done
1111 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1112 else
1113 rm -rf "$@"
1114 fi
1115 }
1116
1117
1118 tclock() {
1119 clear
1120 date +%l:%_M
1121 len=60
1122 # this goes to full width
1123 #len=${1:-$((COLUMNS -7))}
1124 x=1
1125 while true; do
1126 if (( x == len )); then
1127 end=true
1128 d="$(date +%l:%_M) "
1129 else
1130 end=false
1131 d=$(date +%l:%M:%_S)
1132 fi
1133 echo -en "\r"
1134 echo -n "$d"
1135 for ((i=0; i<x; i++)); do
1136 if (( i % 6 )); then
1137 echo -n _
1138 else
1139 echo -n .
1140 fi
1141 done
1142 if $end; then
1143 echo
1144 x=1
1145 else
1146 x=$((x+1))
1147 fi
1148 sleep 5
1149 done
1150 }
1151
1152
1153 te() {
1154 # test existence / exists
1155 local ret=0
1156 for x in "$@"; do
1157 [[ -e "$x" || -L "$x" ]] || ret=1
1158 done
1159 return $ret
1160 }
1161
1162 testmail() {
1163 declare -gi _seq; _seq+=1
1164 echo "test body" | m mail -s "test mail from $HOSTNAME, $_seq" "${1:-root@localhost}"
1165 }
1166
1167 tm() {
1168 # timer in minutes
1169 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3 --loop=no) > /dev/null 2>&1 &
1170 }
1171
1172
1173 tu() {
1174 local s;
1175 local dir="$(dirname "$1")"
1176 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1177 s=s;
1178 fi
1179 $s teeu "$@"
1180 }
1181
1182 tx() { # toggle set -x, and the prompt so it doesn't spam
1183 if [[ $- == *x* ]]; then
1184 set +x
1185 PROMPT_COMMAND=prompt_command
1186 else
1187 unset PROMPT_COMMAND
1188 PS1="\w \$ "
1189 set -x
1190 fi
1191 }
1192
1193 psnetns() {
1194 # show all processes in the network namespace $1.
1195 # blank entries appear to be subprocesses/threads
1196 local x netns
1197 netns=$1
1198 ps -w | head -n 1
1199 s find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1200 while read l; do
1201 x=$(ps -w --no-headers -p $l);
1202 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1203 done
1204 }
1205
1206 m() { printf "%s\n" "$*"; "$@"; }
1207
1208 vpnbash() {
1209 m s nsenter -t $(pgrep openvpn) -n -m bash
1210 # note, if we wanted to run a graphical program,
1211 # instead of bash, we could use
1212 # gksudo -u ${SUDO_USER:-$USER} "$@"
1213 }
1214
1215
1216 trg() { transmission-remote-gtk&r; }
1217
1218 # transmission() {
1219 # local pid=$(cat /var/lib/transmission-daemon/transmission-daemon.pid)
1220 # if [[ $pid && -e /proc/$pid ]]; then
1221 # echo "noop. already running."
1222 # return
1223 # fi
1224
1225 # local NAME=transmission-daemon
1226 # local DAEMON=/usr/bin/$NAME
1227 # local duser=debian-transmission
1228
1229 # [ -e /etc/default/$NAME ] && . /etc/default/$NAME
1230 # s ip netns exec vpn sudo -u $duser ionice -c 3 nice -n 19 $DAEMON $OPTIONS
1231 # }
1232
1233 virshrm() {
1234 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1235 }
1236
1237 vm-set-listen(){
1238 local t=$(mktemp)
1239 local vm=$1
1240 local ip=$2
1241 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1242 sed -r "s/listen='[^']+/listen='$ip/"> $t
1243 s virsh undefine $vm
1244 s virsh define $t
1245 }
1246
1247
1248 vmshare() {
1249 vm-set-listen $1 0.0.0.0
1250 }
1251
1252
1253 vmunshare() {
1254 vm-set-listen $1 127.0.0.1
1255 }
1256
1257 vpn() {
1258 s systemctl start openvpn@client&
1259 journalctl --unit=openvpn@client -f -n0
1260 }
1261
1262
1263 vpnoff() {
1264 s systemctl stop openvpn@client
1265 }
1266
1267
1268 vrm() {
1269 virsh destroy $1
1270 virsh undefine $1
1271 }
1272
1273
1274
1275 vspicy() { # usage: VIRSH_DOMAIN
1276 # connect to vms made with virt-install
1277 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1278 sed -r "s/.*port='([0-9]+).*/\1/")
1279 }
1280
1281
1282 whatismyip() { curl ipecho.net/plain ; echo; }
1283
1284
1285 #############################
1286 ######### misc stuff ########
1287 #############################
1288
1289 if [[ $- == *i* ]]; then
1290 # commands to run when bash exits normally
1291 trap "hl" EXIT
1292 fi
1293
1294
1295 # temporary variables to test colorization
1296 # some copied from gentoo /etc/bash/bashrc,
1297 use_color=false
1298 # dircolors --print-database uses its own built-in database
1299 # instead of using /etc/DIR_COLORS. Try to use the external file
1300 # first to take advantage of user additions.
1301 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1302 match_lhs=""
1303 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1304 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1305 [[ -z ${match_lhs} ]] \
1306 && type -P dircolors >/dev/null \
1307 && match_lhs=$(dircolors --print-database)
1308 # test if our $TERM is in the TERM values in dircolor
1309 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1310
1311
1312 if ${use_color} && [[ $- == *i* ]]; then
1313
1314 if [[ $XTERM_VERSION == Cygwin* ]]; then
1315 get_term_color() {
1316 for x in "$@"; do
1317 case $x in
1318 underl) echo -n $'\E[4m' ;;
1319 bold) echo -n $'\E[1m' ;;
1320 red) echo -n $'\E[31m' ;;
1321 green) echo -n $'\E[32m' ;;
1322 blue) echo -n $'\E[34m' ;;
1323 cyan) echo -n $'\E[36m' ;;
1324 yellow) echo -n $'\E[33m' ;;
1325 purple) echo -n $'\E[35m' ;;
1326 nocolor) echo -n $'\E(B\E[m' ;;
1327 esac
1328 done
1329 }
1330
1331 else
1332 get_term_color() {
1333 for x in "$@"; do
1334 case $x in
1335 underl) echo -n $(tput smul) ;;
1336 bold) echo -n $(tput bold) ;;
1337 red) echo -n $(tput setaf 1) ;;
1338 green) echo -n $(tput setaf 2) ;;
1339 blue) echo -n $(tput setaf 4) ;;
1340 cyan) echo -n $(tput setaf 6) ;;
1341 yellow) echo -n $(tput setaf 3) ;;
1342 purple) echo -n $(tput setaf 5) ;;
1343 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1344 esac
1345 done
1346 }
1347 fi
1348 else
1349 get_term_color() {
1350 :
1351 }
1352 fi
1353 # Try to keep environment pollution down, EPA loves us.
1354 unset safe_term match_lhs use_color
1355
1356
1357
1358
1359
1360
1361 ###############
1362 # prompt ######
1363 ###############
1364
1365
1366 if [[ $- == *i* ]]; then
1367 # git branch/status prompt function
1368 if [[ $OS != Windows_NT ]]; then
1369 GIT_PS1_SHOWDIRTYSTATE=true
1370 fi
1371 # arch source lopip show -fcation
1372 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1373 # fedora/debian source
1374 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1375
1376 # in case we didn't source git-prompt.sh
1377 if ! declare -f __git_ps1 > /dev/null; then
1378 __git_ps1() {
1379 :
1380 }
1381 fi
1382
1383 # this needs to come before next ps1 stuff
1384 # this stuff needs bash 4, feb 2009,
1385 # old enough to no longer condition on $BASH_VERSION anymore
1386 shopt -s autocd
1387 shopt -s dirspell
1388 PS1='\w'
1389 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1390 PROMPT_DIRTRIM=2
1391 bind -m vi-command B:shell-backward-word
1392 bind -m vi-command W:shell-forward-word
1393 fi
1394
1395 if [[ $SSH_CLIENT ]]; then
1396 PS1="\h $PS1"
1397 fi
1398
1399 prompt_command() {
1400 local return=$? # this MUST COME FIRST
1401 local psc pst ps_char ps_color stale_subvol
1402 unset IFS
1403 history -a # save history
1404
1405 # for titlebar
1406 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1407 # from the screen man page
1408 if [[ $TERM == screen* ]]; then
1409 local title_escape="\033]..2;"
1410 else
1411 local title_escape="\033]0;"
1412 fi
1413 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1414 fi
1415
1416
1417 case $return in
1418 0) ps_color="$(get_term_color blue)"
1419 ps_char='\$'
1420 ;;
1421 1) ps_color="$(get_term_color green)"
1422 ps_char="$return \\$"
1423 ;;
1424 *) ps_color="$(get_term_color yellow)"
1425 ps_char="$return \\$"
1426 ;;
1427 esac
1428 if [[ ! -O . ]]; then # not owner
1429 if [[ -w . ]]; then # writable
1430 ps_color="$(get_term_color bold red)"
1431 else
1432 ps_color="$(get_term_color bold green)"
1433 fi
1434 fi
1435 # I would set nullglob, but bash has had bugs where that
1436 # doesn't work if not in top level.
1437 if [[ -e /nocow/btrfs-stale ]] && ((`ls -AUq /nocow/btrfs-stale|wc -l`)); then
1438 ps_char="! $ps_char"
1439 fi
1440 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1441 # emacs completion doesn't like the git prompt atm, so disabling it.
1442 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1443 }
1444 PROMPT_COMMAND=prompt_command
1445 fi
1446
1447
1448
1449 ###########################################
1450 # stuff that makes sense to be at the end #
1451 ###########################################
1452 if [[ "$SUDOD" ]]; then
1453 cd "$SUDOD"
1454 unset SUDOD
1455 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1456 cd /a
1457 fi
1458
1459
1460 # best practice
1461 unset IFS
1462
1463
1464 # if someone exported $SOE, catch errors
1465 if [[ $SOE ]]; then
1466 errcatch
1467 fi
1468
1469 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1470 # https://github.com/rubygems/rubygems/pull/1002
1471 # further problems: installing multi-user ruby and user ruby,
1472 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1473 # There a third hybrid form, which passenger error suggested I use,
1474 # but it didn't actually work.
1475
1476 # in cased I never need this
1477 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1478 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1479 # source $(rvm 1.9.3 do rvm env --path)
1480 #fi
1481
1482 # based on warning from rvmsudo
1483 export rvmsudo_secure_path=1
1484
1485 # for other script I wrote
1486 #export ACME_TINY_PATH=/a/opt/acme-tiny
1487 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1488
1489 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1490 source "/usr/local/rvm/scripts/rvm"
1491 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1492 source $HOME/.rvm/scripts/rvm
1493 fi
1494
1495
1496 path_add --end ~/.npm-global
1497
1498
1499 # didn't get drush working, if I did, this seems like the
1500 # only good thing to include for it.
1501 # Include Drush completion.
1502 # if [ -f "/home/ian/.drush/drush.complete.sh" ] ; then
1503 # source /home/ian/.drush/drush.complete.sh
1504 # fi
1505
1506
1507 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1508 # i added an extra condition as gentoo xorg guide says depending on
1509 # $DISPLAY is fragile.
1510 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1511 exec startx
1512 fi
1513
1514
1515 # ensure no bad programs appending to this file will have an affect
1516 return 0