fixes and new bashrc 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 export WCDHOME=/a
174 # based on readme.debian. dunno if this will break on other distros.
175 _x=/usr/share/wcd/wcd-include.sh
176 if [[ -e $_x ]]; then source $_x; fi
177
178
179 ###############
180 ### aliases ###
181 ###############
182
183 # very few aliases, functions are always preferred.
184
185 # ancient stuff.
186 if [[ $OS == Windows_NT ]]; then
187 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
188 export DISPLAY=nt
189 alias j='command cygpath'
190 alias t='command cygstart'
191 alias cygstart='echo be quick, use the alias "t" instead :\)'
192 alias cygpath='echo be quick, use the alias "j" instead :\)'
193 fi
194
195
196
197 # keep this in mind? good for safety.
198 # alias cp='cp -i'
199 # alias mv='mv -i'
200
201
202 # remove any default aliases for these
203 unalias ls ll grep &>/dev/null ||:
204
205
206
207
208
209
210
211
212
213 #####################
214 ### functions ####
215 #####################
216
217
218 ..() { c ..; }
219 ...() { c ../..; }
220 ....() { c ../../..; }
221 .....() { c ../../../..; }
222 ......() { c ../../../../..; }
223
224
225 # file cut copy and paste, like the text buffers :)
226 # I havn't tested these.
227 _fbufferinit() { # internal use by
228 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
229 rm -rf "$my_f_tempdir"/*
230 }
231 fcp() { # file cp
232 _fbufferinit
233 cp "$@" "$my_f_tempdir"/
234 }
235 fct() { # file cut
236 _fbufferinit
237 mv "$@" "$my_f_tempdir"/
238 }
239 fpst() { # file paste
240 [[ $2 ]] && { echo too many arguments; return 1; }
241 target=${1:-.}
242 cp "$my_f_tempdir"/* "$target"
243 }
244
245
246 # todo, update this
247 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
248
249
250 _cdiff-prep() {
251 # join options which are continued to multiples lines onto one line
252 local first=true
253 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
254 # remove leading spaces/tabs. assumes extglob
255 if [[ $line == "[ ]*" ]]; then
256 line="${line##+( )}"
257 fi
258 if $first; then
259 pastline="$line"
260 first=false
261 elif [[ $line == *=* ]]; then
262 echo "$pastline" >> "$2"
263 pastline="$line"
264 else
265 pastline="$pastline $line"
266 fi
267 done
268 echo "$pastline" >> "$2"
269 }
270
271 _khfix_common() {
272 local h=${1##*@}
273 local x
274 ssh-keygen -R $h -f $(readlink -f ~/.ssh/known_hosts)
275 x=$(timeout 1 ssh -oBatchMode=yes -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p")
276 if [[ ! $x ]]; then
277 echo "khfix: ssh failed"
278 return 1
279 fi
280 echo "khfix: removing key for $x"
281 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
282 }
283 khfix() { # known hosts fix
284 _khfix_common "$@" || return 1
285 ssh $1 :
286 }
287 khcopy() {
288 _khfix_common "$@"
289 ssh-copy-id $1
290 }
291
292 a() {
293 beet "${@}"
294 }
295
296 ack() { ack-grep "$@"; }
297
298 astudio() {
299 # googling android emulator libGL error: failed to load driver: r600
300 # lead to http://stackoverflow.com/a/36625175/14456
301 export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1
302 /a/opt/android-studio/bin/studio.sh "$@" &r;
303 }
304
305 b() {
306 # backwards
307 c -
308 }
309
310 bkrun() {
311 # use -p from interactive shell
312 btrbk-run -p "$@"
313 }
314
315 bfg() { java -jar /a/opt/bfg-1.12.14.jar "$@"; }
316
317 btc() {
318 local f=/etc/bitcoin/bitcoin.conf
319 # importprivkey will timeout if using the default of 15 mins.
320 # upped it to 1 hour.
321 bitcoin-cli -rpcclienttimeout=60000 -$(s grep rpcuser= $f) -$(s grep rpcpassword= $f) "$@"
322 }
323
324 btcusd() {
325 local price
326 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
327 printf "$%s\n" "$price"
328 if [[ $1 ]]; then
329 printf "$%.2f\n" "$(echo "scale=4; $price * $1"| bc -l)"
330 fi
331 }
332 usdbtc() {
333 local price
334 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
335 printf "$%s\n" "$price"
336 if [[ $1 ]]; then
337 # 100 mil satoshi / btc. 8 digits after the 1.
338 printf "%.8f btc\n" "$(echo "scale=10; $1 / $price "| bc -l)"
339 fi
340 }
341 satoshi() {
342 local price
343 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
344 price=$(echo "scale=10; $price * 0.00000001"| bc -l)
345 printf "$%f\n" "$price"
346 if [[ $1 ]]; then
347 printf "$%.2f\n" "$(echo "scale=10; $price * $1"| bc -l)"
348 fi
349 }
350
351
352 # c. better cd
353 if [[ $RLC_INSIDE_EMACS ]]; then
354 c() { wcd -c -z 50 -o "$@"; }
355 else
356 # lets see what the fancy terminal does from time to time
357 c() { wcd -c -z 50 "$@"; }
358 fi
359
360 caa() { git commit --amend --no-edit -a; }
361
362 caf() {
363 find -L $1 -type f -not \( -name .svn -prune -o -name .git -prune \
364 -o -name .hg -prune -o -name .editor-backups -prune \
365 -o -name .undo-tree-history -prune \) \
366 -exec bash -lc 'hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
367
368 }
369
370 calc() { echo "scale=3; $*" | bc -l; }
371 # no having to type quotes, but also no command history:
372 clc() {
373 local x
374 read -r x
375 echo "scale=3; $x" | bc -l
376 }
377
378 cam() {
379 git commit -am "$*"
380 }
381
382 ccat () { # config cat. see a config without extra lines.
383 grep '^\s*[^[:space:]#]' "$@"
384 }
385
386 cdiff() {
387 # diff config files,
388 # setup for format of postfix, eg:
389 # option = stuff[,]
390 # [more stuff]
391 local pastline
392 local unified="$(mktemp)"
393 local f1="$(mktemp)"
394 local f2="$(mktemp)"
395 _cdiff-prep "$1" "$f1"
396 _cdiff-prep "$2" "$f2"
397 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
398 while IFS= read -r line; do
399 # the default bright red / blue doesn't work in emacs shell
400 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
401 done < "$unified"
402 }
403
404 cgpl()
405 {
406 if (($#)); then
407 cp /a/bin/data/COPYING "$@"
408 else
409 cp /a/bin/data/COPYING .
410 fi
411 }
412 capache()
413 {
414 if (($#)); then
415 cp /a/bin/data/LICENSE "$@"
416 else
417 cp /a/bin/data/LICENSE .
418 fi
419 }
420 chown() {
421 # makes it so chown -R symlink affects the symlink and its target.
422 if [[ $1 == -R ]]; then
423 shift
424 command chown -h "$@"
425 command chown -R "$@"
426 else
427 command chown "$@"
428 fi
429 }
430
431 cim() {
432 git commit -m "$*"
433 }
434
435 cl() {
436 # choose recent directory. cl = cd list
437 c =
438 }
439
440 chrome() {
441 CHROMIUM_FLAGS='--enable-remote-extensions' chromium &r
442 }
443
444 d() { builtin bg; }
445 complete -A stopped -P '"%' -S '"' d
446
447 dat() { # do all tee, for more complex scripts
448 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
449 }
450 da() { # do all
451 local host
452 "$@"
453 for host in x2 tp treetowl; do
454 ssh $host "$@"
455 done
456 }
457
458 dc() {
459 diff --strip-trailing-cr -w "$@" # diff content
460 }
461
462 debian_pick_mirror () {
463 # netselect-apt finds a fast mirror.
464 # but we need to replace the mirrors ourselves,
465 # because it doesn't do that. best it can do is
466 # output a basic sources file
467 # here we get the server it found, get the main server we use
468 # then substitute all instances of one for the other in the sources file
469 # and backup original to /etc/apt/sources.list-original.
470 # this is idempotent. the only way to identify debian sources is to
471 # note the original server, so we put it in a comment so we can
472 # identify it later.
473 local file=$(mktemp -d)/f # safe way to get file name without creating one
474 sudo netselect-apt -o "$file" || return 1
475 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
476 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
477 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
478 sudo apt-get update
479 }
480
481 despace() {
482 local x y
483 for x in "$@"; do
484 y="${x// /_}"
485 safe_rename "$x" "$y"
486 done
487 }
488
489 dt() {
490 date "+%A, %B %d, %r" "$@"
491 }
492
493 dus() { # du, sorted, default arg of
494 du -sh ${@:-*} | sort -h
495 }
496
497
498
499 e() { echo "$@"; }
500
501
502 ediff() {
503 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
504 emacs --eval "(ediff-files \"$1\" \"$2\")"
505 }
506
507
508 envload() { # load environment from a previous: export > file
509 local file=${1:-$HOME/.${USER}_env}
510 eval "$(export | sed 's/^declare -x/export -n/')"
511 while IFS= read -r line; do
512 # declare -x makes variables local to a function
513 eval ${line/#declare -x/export}
514 done < "$file"
515 }
516
517 f() {
518 # cd forward
519 c +
520 }
521
522 fa() {
523 # find array. make an array of file names found by find into $x
524 # argument: find arguments
525 # return: find results in an array $x
526 while read -rd ''; do
527 x+=("$REPLY");
528 done < <(find "$@" -print0);
529 }
530
531 faf() { # find all files
532 find -L $1 -type f -not \( -name .svn -prune -o -name .git -prune \
533 -o -name .hg -prune -o -name .editor-backups -prune \
534 -o -name .undo-tree-history -prune \) 2>/dev/null
535 }
536
537 fastboot() { /a/opt/androidsdk/platform-tools/fastboot "$@"; }
538
539
540 # List of apps to install/update
541 # Create from existing manually installed apps by doing
542 # fdroidcl search -i, then manually removing
543 # automatically installed/preinstalled apps
544 fdroid_pkgs=(
545 at.bitfire.davdroid
546 com.fsck.k9
547 com.ichi2.anki
548 com.notecryptpro
549 com.nutomic.syncthingandroid
550 com.termux
551 de.danoeh.antennapod
552 de.marmaro.krt.ffupdater
553 im.vector.alpha # riot
554 me.ccrama.redditslide
555 net.gaast.giggity
556 net.osmand.plus
557 org.dmfs.tasks # caldav tasks thing
558 org.fdroid.fdroid
559 org.quantumbadger.redreader
560 org.secuso.privacyfriendlyweather
561 org.smssecure.smssecure
562 org.fedorahosted.freeotp
563 com.ghostsq.commander
564 me.tripsit.tripmobile
565 # https://forum.xda-developers.com/android/software-hacking/wip-selinux-capable-superuser-t3216394
566 me.phh.superuser
567 )
568 fdup() {
569 local -A installed updated
570 local p
571 fdroidcl update
572 for p in $(fdroidcl search -i| grep -o "^\S\+"); do
573 installed[$p]=true
574 done
575 for p in $(fdroidcl search -u| grep -o "^\S\+"); do
576 updated[$p]=false
577 done
578 for p in ${fdroid_pkgs[@]}; do
579 ${installed[$p]:-false} || fdroidcl install $p
580 done
581 for p in ${!installed[@]}; do
582 ${updated[$p]:-true} || fdroidcl upgrade $p
583 done
584 }
585
586 ff() {
587 if type -P firefox &>/dev/null; then
588 firefox "$@"
589 else
590 iceweasel "$@"
591 fi
592 }
593
594
595
596 fn() {
597 firefox -P alt "$@" >/dev/null 2>&1
598 }
599
600
601 fsdiff () {
602 local missing=false
603 local dname="${PWD##*/}"
604 local m="/a/tmp/$dname-missing"
605 local d="/a/tmp/$dname-diff"
606 [[ -e $d ]] && rm "$d"
607 [[ -e $m ]] && rm "$m"
608 local msize=0
609 local fsfile
610 while read -r line; do
611 fsfile="$1${line#.}"
612 if [[ -e "$fsfile" ]]; then
613 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
614 else
615 missing=true
616 echo "$line" >> "$m"
617 msize=$((msize + 1))
618 fi
619 done < <(find -type f )
620 if $missing; then
621 echo "$m"
622 (( msize <= 100 )) && cat $m
623 fi
624 }
625 fsdiff-test() {
626 # expected output, with different tmp dirs
627 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
628 # /a/tmp/tmp.qLDkYxBYPM-missing
629 # ./b
630 cd $(mktemp -d)
631 echo ok > a
632 echo nok > b
633 mkdir c
634 echo ok > c/d
635 local x=$(mktemp -d)
636 mkdir $x/c
637 echo different > $x/c/d
638 echo ok > $x/a
639 fsdiff $x
640 }
641 rename-test() {
642 # test whether missing files were renamed, generally for use with fsdiff
643 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
644 # echos non-renamed files
645 local x y found
646 unset sums
647 for x in "$2"/*; do
648 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
649 done
650 while read -r line; do
651 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
652 renamed=false
653 for x in "${sums[@]}"; do
654 if [[ $missing_sum == "$x" ]]; then
655 renamed=true
656 break
657 fi
658 done
659 $renamed || echo "$line"
660 done < "$1"
661 return 0
662 }
663
664 feh() {
665 # F = fullscren, z = random, Z = auto zoom
666 command feh -FzZ "$@"
667 }
668
669 funce() {
670 # like -e for functions. returns on error.
671 # at the end of the function, disable with:
672 # trap ERR
673 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
674 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
675 trap ERR
676 return' ERR
677 }
678
679
680 fw() {
681 firefox -P default "$@" >/dev/null 2>&1
682 }
683
684 getdir () {
685 local help="Usage: getdir [--help] PATH
686 Output the directory of PATH, or just PATH if it is a directory."
687 if [[ $1 == --help ]]; then
688 echo "$help"
689 return 0
690 fi
691 if [[ $# -ne 1 ]]; then
692 echo "getdir error: expected 1 argument, got $#"
693 return 1
694 fi
695 if [[ -d $1 ]]; then
696 echo "$1"
697 else
698 local dir="$(dirname "$1")"
699 if [[ -d $dir ]]; then
700 echo "$dir"
701 else
702 echo "getdir error: directory does not exist"
703 return 1
704 fi
705 fi
706 }
707
708 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
709 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
710 local gitroot
711 gitroot || return 1 # function to set gitroot
712 builtin cd "$gitroot"
713 git symbolic-ref HEAD refs/heads/$1
714 rm .git/index
715 git clean -fdx
716 }
717
718 gitroot() {
719 local help="Usage: gitroot [--help]
720 Print the full path to the root of the current git repo
721
722 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
723 and works in older versions of git which did not have that."
724 if [[ $1 == --help ]]; then
725 echo "$help"
726 return
727 fi
728 local p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
729 [[ $p != /* ]] && p=$PWD
730 echo "${p%%/.git}"
731 }
732
733 gmacs() {
734 # quit will prompt if the program crashes.
735 gdb -ex=r -ex=quit --args emacs "$@"; r;
736 }
737
738 gdkill() {
739 # kill the emacs daemon
740 pk1 emacs --daemon
741 }
742
743 gse() {
744 git send-email --notes '--envelope-sender=<ian@iankelling.org>' \
745 --suppress-cc=self "$@"
746 }
747
748 gr() {
749 grep -iIP --color=auto "$@"
750 }
751
752 grr() {
753 if [[ ${#@} == 1 ]]; then
754 grep -riIP --color=auto "$@" .
755 else
756 grep -riIP --color=auto "$@"
757 fi
758 }
759
760 hstatus() {
761 # do git status on published repos
762 cd /a/bin/githtml
763 for x in !(forks) forks/* ian-specific/*; do
764 cd `readlink -f $x`/..
765 hr
766 echo $x
767 i status
768 cd /a/bin/githtml
769 done
770 }
771
772 hl() { # history limit. Write extra history to archive file.
773 # todo: this is not working or not used currently
774 local max_lines linecount tempfile prune_lines x
775 local harchive="${HISTFILE}_archive"
776 for x in "$HISTFILE" "$harchive"; do
777 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
778 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
779 echo "error in hl: history file \$x:$x no good"
780 return 1
781 fi
782 done
783 history -a # save history
784 max_lines=$HISTFILELINES
785 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
786 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
787 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
788 if (($linecount > $max_lines)); then
789 prune_lines=$(($linecount - $max_lines))
790 head -n $prune_lines "$HISTFILE" >> "$harchive" \
791 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
792 fi
793 }
794
795 hr() { # horizontal row. used to break up output
796 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq ${COLUMNS:-60})
797 echo
798 }
799
800 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
801
802
803 i() { git "$@"; }
804 # modified from ~/local/bin/git-completion.bash
805 # other completion commands are mostly taken from bash_completion package
806 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
807 || complete -o default -o nospace -F _git i
808
809 if ! type service &>/dev/null; then
810 service() {
811 echo actually running: systemctl $2 $1
812 systemctl $2 $1
813 }
814 fi
815
816 ic() {
817 # fast commit all
818 git commit -am "$*"
819 }
820
821 idea() {
822 /a/opt/idea-IC-163.7743.44/bin/idea.sh "$@" &r
823 }
824
825 ifn() {
826 # insensitive find
827 find -L . -not \( -name .svn -prune -o -name .git -prune \
828 -o -name .hg -prune -o -name .editor-backups -prune \
829 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
830 }
831
832
833 if [[ $OS == Windows_NT ]]; then
834 # cygstart wrapper
835 cs() {
836 cygstart "$@" &
837 }
838 xp() {
839 explorer.exe .
840 }
841 # launch
842 o() {
843 local x=(*$1*)
844 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
845 cygstart *$1* &
846 }
847 else
848 o() {
849 if type gvfs-open &> /dev/null ; then
850 gvfs-open "$@"
851 else
852 xdg-open "$@"
853 fi
854 # another alternative is run-mailcap
855 }
856 fi
857
858 net-dev-info() {
859 e "lspci -nnk|gr -iA2 net"
860 lspci -nnk|gr -iA2 net
861 hr
862 e "s lshw -C network"
863 hr
864 s lshw -C network
865
866 }
867
868 istext() {
869 grep -Il "" "$@" &>/dev/null
870 }
871
872 jtail() {
873 journalctl -n 10000 -f "$@" | grep -Evi "^(\S+\s+){4}(sudo|sshd|cron)"
874 }
875
876
877 l() {
878 if [[ $PWD == /[iap] ]]; then
879 command ls -A --color=auto -I lost+found "$@"
880 else
881 command ls -A --color=auto "$@"
882 fi
883 }
884
885
886 lcn() { locate -i "*$**"; }
887
888 lld() { ll -d "$@"; }
889
890 low() { # make filenames lowercase, remove bad chars
891 local f new
892 for f in "$@"; do
893 new="${f,,}" # downcase
894 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
895 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
896 new="${new%"${new##*[[:alnum:]]}"}"
897 # remove bad underscores, like __ and _._
898 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
899 safe_rename "$f" "$new" || return 1
900 done
901 return 0
902 }
903
904 lower() { # make first letter of filenames lowercase.
905 local x
906 for x in "$@"; do
907 if [[ ${x::1} == [A-Z] ]]; then
908 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
909 safe_rename "$x" "$y" || return 1
910 fi
911 done
912 }
913
914
915 k() { # history search
916 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80;
917 }
918
919
920 make-targets() {
921 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
922 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
923 }
924
925 mbenable() {
926 mb=$1
927 dst=/m/4e/$1
928 src=/m/md/$1
929 set -x
930 mv -T $src $dst || { set +x; return 1; }
931 ln -s -T $dst $src
932 set +x
933 }
934 mbdisable() {
935 mb=$1
936 dst=/m/md/$1
937 src=/m/4e/$1
938 set -x
939 if [[ -L $dst ]]; then rm $dst; fi
940 mv -T $src $dst
941 set +x
942 }
943
944
945 mkc() {
946 mkdir "$1"
947 c "$1"
948 }
949
950 mkdir() { command mkdir -p "$@"; }
951
952 pithos() {
953 cd /
954 export PYTHONPATH=/a/opt/Pithosfly
955 python3 -m pithos&r
956 }
957
958 pakaraoke() {
959 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
960 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
961 }
962
963
964 pfind() { #find *$1* in $PATH
965 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
966 local pathArray
967 IFS=: pathArray=($PATH); unset IFS
968 find "${pathArray[@]}" -iname "*$1*"
969 }
970
971 pk1() {
972 local pid
973 pid=($(pgrep -f "$*"))
974 case ${#pid[@]} in
975 1)
976 ps -F $pid
977 m kill $pid
978 ;;
979 0) echo "no pid found" ;;
980 *)
981 ps -F ${pid[@]}
982 ;;
983 esac
984 }
985
986 pick-trash() {
987 # trash-restore lists everything that has been trashed at or below CWD
988 # This picks out files just in CWD, not subdirectories,
989 # which also match grep $1, usually use $1 for a time string
990 # which you get from running restore-trash once first
991 local name x ask
992 local nth=1
993 # last condition is to not ask again for ones we skipped
994 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
995 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
996 name="$(echo "$name" | head -n $nth | tail -n 1 )"
997 read -p "$name [Y/n] " ask
998 if [[ ! $ask || $ask == [Yy] ]]; then
999 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
1000 echo $x | restore-trash > /dev/null
1001 elif [[ $ask == [Nn] ]]; then
1002 nth=$((nth+1))
1003 else
1004 return
1005 fi
1006 done
1007 }
1008
1009 pub() {
1010 rld /a/h/_site/ li:/var/www/iankelling.org/html
1011 }
1012
1013 pubip() { curl -4s https://icanhazip.com; }
1014 whatismyip() { pubip; }
1015
1016 pumpa() {
1017 # fixes the menu bar in xmonad. this won\'t be needed when xmonad
1018 # packages catches up on some changes in future (this is written in
1019 # 4/2017)
1020 #
1021 # geekosaur: so you'll want to upgrade to xmonad 0.13 or else use a
1022 # locally modified XMonad.Hooks.ManageDocks that doesn't set the
1023 # work area; turns out it's impossible to set correctly if you are
1024 # not a fully EWMH compliant desktop environment
1025 #
1026 # geekosaur: chrome shows one failure mode, qt/kde another, other
1027 # gtk apps a third, ... I came up with a setting that works for me
1028 # locally but apparently doesn't work for others, so we joined the
1029 # other tiling window managers in giving up on setting it at all
1030 #
1031 xprop -root -remove _NET_WORKAREA
1032 command pumpa &r
1033 }
1034
1035
1036 pwgen() {
1037 # -m = min length
1038 # -x = max length
1039 # -t = print pronunciation
1040 apg -m 12 -x 16 -t
1041 }
1042
1043 pwlong() {
1044 # -M CLN = use Caps, Lowercase, Numbers
1045 # -n 1 = 1 password
1046 # -a 1 = use random instead of pronounceable algorithm
1047 apg -m 50 -x 70 -n 1 -a 1 -M CLN
1048 }
1049
1050
1051 q() { # start / launch a program in the backround and redir output to null
1052 "$@" &> /dev/null &
1053 }
1054
1055 r() {
1056 exit "$@" 2>/dev/null
1057 }
1058
1059 rbpipe() { rbt post -o --diff-filename=- "$@"; }
1060 rbp() { rbt post -o "$@"; }
1061
1062 rl() {
1063 # rsync, root is required to keep permissions right.
1064 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1065 # --no-times --delete
1066 # basically, make an exact copy, use checksums instead of file times to be more accurate
1067 rsync -ahvic --delete "$@"
1068 }
1069 rld() {
1070 # like rlu, but don't delete files on the target end which
1071 # do not exist on the original end.
1072 rsync -ahvic "$@"
1073 }
1074 complete -F _rsync -o nospace rld rl rlt
1075
1076 rlt() {
1077 # rl without preserving modification time.
1078 rsync -ahvic --delete --no-t "$@"
1079 }
1080
1081 rlu() { # [OPTS] HOST PATH
1082 # eg. rlu -opts frodo /testpath
1083 # relative paths will expanded with readlink -f.
1084 # useful for selectively sending dirs which have been synced with unison,
1085 # where the path is the same on both hosts.
1086 opts=("${@:1:$#-2}") # 1 to last -2
1087 path="${@:$#}" # last
1088 host="${@:$#-1:1}" # last -1
1089 if [[ $path == .* ]]; then
1090 path=$(readlink -f $path)
1091 fi
1092 # rync here uses checksum instead of time so we don't mess with
1093 # unison relying on time as much. g is for group, same reason
1094 # to keep up with unison.
1095 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1096 }
1097
1098 r2eadd() { # usage: name url
1099 # initial setup of rss2email:
1100 # r2e new r2e@iankelling.org
1101 # that initializes files, and sets default email.
1102 # Would have been simpler to just leave it off since i\'m not
1103 # using the default email. Symlinks won\'t work, so we use binds.
1104 # mkdir /p/c/binds/.config/
1105 # mv ~/.config/rss2email.cfg /p/c/binds/.config/
1106 # mkdir /p/c/binds/.local/share/
1107 # mv ~/.local/share/rss2email.json /p/c/binds/.local/share/
1108 # conflink
1109 r2e add $1 "$2" $1@r2e.iankelling.org
1110 # get up to date and don't send old entries now:
1111 r2e run --no-send $1
1112 }
1113 r2e() { command r2e -d /p/c/rss2email.json -c /p/c/rss2email.cfg "$@"; }
1114
1115 rspicy() { # usage: HOST DOMAIN
1116 # connect to spice vm remote host. use vspicy for local host
1117 local port=$(ssh $1<<EOF
1118 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
1119 sed -rn "s/.*port='([0-9]+).*/\1/p"
1120 EOF
1121 )
1122 if [[ $port ]]; then
1123 spicy -h $1 -p $port
1124 else
1125 echo "error: no port found. check that the domain is running."
1126 fi
1127 }
1128
1129 s() {
1130 # background
1131 # I use a function because otherwise we can't use in a script,
1132 # can't assign to variable.
1133 #
1134 # note: gksudo is recommended for X apps because it does not set the
1135 # home directory to the same, and thus apps writing to ~ fuck things up
1136 # with root owned files.
1137 #
1138 if [[ $EUID != 0 || $1 == -* ]]; then
1139 SUDOD="$PWD" sudo -i "$@"
1140 else
1141 "$@"
1142 fi
1143 }
1144
1145 safe_rename() { # warn and don't rename if file exists.
1146 # mv -n exists, but it's silent
1147 if [[ $# != 2 ]]; then
1148 echo safe_rename error: $# args, need 2 >2
1149 return 1
1150 fi
1151 if [[ $1 != $2 ]]; then # yes, we want to silently ignore this
1152 if [[ -e $2 || -L $2 ]]; then
1153 echo "Cannot rename $1 to $2 as it already exists."
1154 else
1155 mv -vi "$1" "$2"
1156 fi
1157 fi
1158 }
1159
1160
1161 sb() { # sudo bash -c
1162 # use sb instead of s is for sudo redirections,
1163 # eg. sb 'echo "ok fine" > /etc/file'
1164 local SUDOD="$PWD"
1165 sudo -i bash -c "$@"
1166 }
1167 complete -F _root_command s sb
1168
1169 scssl() {
1170 # s gem install scss-lint
1171 pushd /a/opt/thoughtbot-guides
1172 git pull --stat
1173 popd
1174 scss-lint -c /a/opt/thoughtbot-guides/style/sass/.scss-lint.yml "$@"
1175 }
1176
1177 ser() {
1178 local s; [[ $EUID != 0 ]] && s=sudo
1179 if type -p systemctl &>/dev/null; then
1180 $s systemctl $1 $2
1181 else
1182 $s service $2 $1
1183 fi
1184 }
1185
1186 sgo() { # service go
1187 service=$1
1188 ser restart $service
1189 if type -p systemctl &>/dev/null; then
1190 ser enable $service
1191 fi
1192 }
1193
1194
1195 shellck() {
1196 # 2086 = unquoted $var
1197 # 2046 = unquoted $(cmd)
1198 # i had -x as an arg, but debian testing(stretch) doesn't support it
1199 shellcheck -e 2086,2046,2068,2006,2119 "$@"
1200 }
1201
1202
1203 slog() {
1204 # log with script. timing is $1.t and script is $1.s
1205 # -l to save to ~/typescripts/
1206 # -t to add a timestamp to the filenames
1207 local logdir do_stamp arg_base
1208 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1209 logdir="/a/dt/"
1210 do_stamp=false
1211 while getopts "lt" option
1212 do
1213 case $option in
1214 l ) arg_base=$logdir ;;
1215 t ) do_stamp=true ;;
1216 esac
1217 done
1218 shift $(($OPTIND - 1))
1219 arg_base+=$1
1220 [[ -e $logdir ]] || mkdir -p $logdir
1221 $do_stamp && arg_base+=$(date +%F.%T%z)
1222 script -t $arg_base.s 2> $arg_base.t
1223 }
1224 splay() { # script replay
1225 #logRoot="$HOME/typescripts/"
1226 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1227 scriptreplay "$1.t" "$1.s"
1228 }
1229
1230 sr() {
1231 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1232 if [[ $# == 0 ]]; then
1233 sudo -E bash -c -l "$(history -p '!!')"
1234 else
1235 echo this command redos last history item. no argument is accepted
1236 fi
1237 }
1238
1239 srm () {
1240 # with -ll, less secure but faster.
1241 command srm -ll "$@"
1242 }
1243
1244 srun() {
1245 scp $2 $1:/tmp
1246 ssh $1 /tmp/${2##*/} "${@:2}"
1247 }
1248
1249 swap() {
1250 local tmp
1251 tmp=$(mktemp)
1252 mv $1 $tmp
1253 mv $2 $1
1254 mv $tmp $2
1255 }
1256
1257 t() {
1258 local x
1259 local -a args
1260 if type -t trash-put >/dev/null; then
1261 # skip args that don't exist, or else trash-put will have an error
1262 for x in "$@"; do
1263 if [[ -e $x || -L $x ]]; then
1264 args+=("$x")
1265 fi
1266 done
1267 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1268 else
1269 rm -rf "$@"
1270 fi
1271 }
1272
1273
1274 tclock() {
1275 clear
1276 date +%l:%_M
1277 len=60
1278 # this goes to full width
1279 #len=${1:-$((COLUMNS -7))}
1280 x=1
1281 while true; do
1282 if (( x == len )); then
1283 end=true
1284 d="$(date +%l:%_M) "
1285 else
1286 end=false
1287 d=$(date +%l:%M:%_S)
1288 fi
1289 echo -en "\r"
1290 echo -n "$d"
1291 for ((i=0; i<x; i++)); do
1292 if (( i % 6 )); then
1293 echo -n _
1294 else
1295 echo -n .
1296 fi
1297 done
1298 if $end; then
1299 echo
1300 x=1
1301 else
1302 x=$((x+1))
1303 fi
1304 sleep 5
1305 done
1306 }
1307
1308
1309 te() {
1310 # test existence / exists
1311 local ret=0
1312 for x in "$@"; do
1313 [[ -e "$x" || -L "$x" ]] || ret=1
1314 done
1315 return $ret
1316 }
1317
1318 testmail() {
1319 declare -gi _seq; _seq+=1
1320 echo "test body" | m mail -s "test mail from $HOSTNAME, $_seq" "${@:-root@localhost}"
1321 # for testing to send from an external address, you can do for example
1322 # -aFrom:ian@iank.bid web-6fnbs@mail-tester.com
1323 # note in exim, you can retry a deferred message
1324 # s exim -M MSG_ID
1325 # MSG_ID is in /var/log/exim4/mainlog, looks like 1ccdnD-0001nh-EN
1326 }
1327
1328 # use -eW to actually modify mailbox
1329 testsievelist() {
1330 sieve-filter ~/sieve/main.sieve "$@" >/a/tmp/slog 2> >(tail) && sed -rn '/^Performed actions:/{n;n;p}' /a/tmp/slog | sort -u
1331 }
1332
1333
1334 testsieve() {
1335 sieve-filter ~/sieve/main.sieve "$@"
1336 }
1337
1338 testexim() {
1339 # testmail above calls sendmail, which is a link to exim/postfix.
1340 # it's docs don't say a way of adding an argument
1341 # to sendmail to turn on debug output. We could make a wrapper, but
1342 # that is a pain. Exim debug args are documented here:
1343 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1344 #
1345 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-building_and_installing_exim.html
1346 # note, for exim daemon, you can turn on debug options by
1347 # adding -d, etc to COMMONOPTIONS in
1348 # /etc/default/exim4
1349 # for testing external mail, you need the to address as final cmdline arg
1350 exim -d+tls -t <<'EOF'
1351 From: root@frodo.lan
1352 To: ian@mail.iankelling.org
1353 Subject: Testing Exim
1354
1355 This is a test message.
1356 EOF
1357 }
1358
1359 tm() {
1360 # timer in minutes
1361 # --no-config
1362 (sleep $(calc "$@ * 60") && mpv --no-config --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1363 }
1364
1365
1366 tu() {
1367 local s;
1368 local dir="$(dirname "$1")"
1369 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1370 s=s;
1371 fi
1372 $s teeu "$@"
1373 }
1374
1375 tx() { # toggle set -x, and the prompt so it doesn't spam
1376 if [[ $- == *x* ]]; then
1377 set +x
1378 PROMPT_COMMAND=prompt_command
1379 else
1380 unset PROMPT_COMMAND
1381 PS1="\w \$ "
1382 set -x
1383 fi
1384 }
1385
1386 psnetns() {
1387 # show all processes in the network namespace $1.
1388 # blank entries appear to be subprocesses/threads
1389 local x netns
1390 netns=$1
1391 ps -w | head -n 1
1392 s find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1393 while read l; do
1394 x=$(ps -w --no-headers -p $l);
1395 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1396 done
1397 }
1398
1399 m() { printf "%s\n" "$*"; "$@"; }
1400
1401
1402 vpncmd() {
1403 m s nsenter -t $(pgrep -f "/usr/sbin/openvpn --suppress-timestamps --nobind --config /etc/openvpn/client/client.conf") -n -m "$@"
1404 }
1405 vpnf() {
1406 vpncmd gksudo -u ian firefox &r
1407 }
1408 vpnbash() {
1409 vpncmd bash
1410 }
1411
1412
1413 trg() { transmission-remote-gtk&r; }
1414
1415 # transmission() {
1416 # local pid=$(cat /var/lib/transmission-daemon/transmission-daemon.pid)
1417 # if [[ $pid && -e /proc/$pid ]]; then
1418 # echo "noop. already running."
1419 # return
1420 # fi
1421
1422 # local NAME=transmission-daemon
1423 # local DAEMON=/usr/bin/$NAME
1424 # local duser=debian-transmission
1425
1426 # [ -e /etc/default/$NAME ] && . /etc/default/$NAME
1427 # s ip netns exec vpn sudo -u $duser ionice -c 3 nice -n 19 $DAEMON $OPTIONS
1428 # }
1429
1430 virshrm() {
1431 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1432 }
1433
1434 vm-set-listen(){
1435 local t=$(mktemp)
1436 local vm=$1
1437 local ip=$2
1438 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1439 sed -r "s/listen='[^']+/listen='$ip/"> $t
1440 s virsh undefine $vm
1441 s virsh define $t
1442 }
1443
1444
1445 vmshare() {
1446 vm-set-listen $1 0.0.0.0
1447 }
1448
1449
1450 vmunshare() {
1451 vm-set-listen $1 127.0.0.1
1452 }
1453
1454 vpn() {
1455 s systemctl start openvpn@client&
1456 journalctl --unit=openvpn@client -f -n0
1457 }
1458
1459
1460 vpnoff() {
1461 s systemctl stop openvpn@client
1462 }
1463
1464
1465 vrm() {
1466 virsh destroy $1
1467 virsh undefine $1
1468 }
1469
1470
1471
1472 vspicy() { # usage: VIRSH_DOMAIN
1473 # connect to vms made with virt-install
1474 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1475 sed -r "s/.*port='([0-9]+).*/\1/")
1476 }
1477
1478
1479 whatismyip() { curl ipecho.net/plain ; echo; }
1480
1481
1482 #############################
1483 ######### misc stuff ########
1484 #############################
1485
1486 if [[ $- == *i* ]]; then
1487 # commands to run when bash exits normally
1488 trap "hl" EXIT
1489 fi
1490
1491
1492 # temporary variables to test colorization
1493 # some copied from gentoo /etc/bash/bashrc,
1494 use_color=false
1495 # dircolors --print-database uses its own built-in database
1496 # instead of using /etc/DIR_COLORS. Try to use the external file
1497 # first to take advantage of user additions.
1498 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1499 match_lhs=""
1500 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1501 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1502 [[ -z ${match_lhs} ]] \
1503 && type -P dircolors >/dev/null \
1504 && match_lhs=$(dircolors --print-database)
1505 # test if our $TERM is in the TERM values in dircolor
1506 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1507
1508
1509 if ${use_color} && [[ $- == *i* ]]; then
1510
1511 if [[ $XTERM_VERSION == Cygwin* ]]; then
1512 get_term_color() {
1513 for x in "$@"; do
1514 case $x in
1515 underl) echo -n $'\E[4m' ;;
1516 bold) echo -n $'\E[1m' ;;
1517 red) echo -n $'\E[31m' ;;
1518 green) echo -n $'\E[32m' ;;
1519 blue) echo -n $'\E[34m' ;;
1520 cyan) echo -n $'\E[36m' ;;
1521 yellow) echo -n $'\E[33m' ;;
1522 purple) echo -n $'\E[35m' ;;
1523 nocolor) echo -n $'\E(B\E[m' ;;
1524 esac
1525 done
1526 }
1527
1528 else
1529 get_term_color() {
1530 for x in "$@"; do
1531 case $x in
1532 underl) echo -n $(tput smul) ;;
1533 bold) echo -n $(tput bold) ;;
1534 red) echo -n $(tput setaf 1) ;;
1535 green) echo -n $(tput setaf 2) ;;
1536 blue) echo -n $(tput setaf 4) ;;
1537 cyan) echo -n $(tput setaf 6) ;;
1538 yellow) echo -n $(tput setaf 3) ;;
1539 purple) echo -n $(tput setaf 5) ;;
1540 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1541 esac
1542 done
1543 }
1544 fi
1545 else
1546 get_term_color() {
1547 :
1548 }
1549 fi
1550 # Try to keep environment pollution down, EPA loves us.
1551 unset safe_term match_lhs use_color
1552
1553
1554
1555
1556
1557
1558 ###############
1559 # prompt ######
1560 ###############
1561
1562
1563 if [[ $- == *i* ]]; then
1564 # git branch/status prompt function
1565 if [[ $OS != Windows_NT ]]; then
1566 GIT_PS1_SHOWDIRTYSTATE=true
1567 fi
1568 # arch source lopip show -fcation
1569 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1570 # fedora/debian source
1571 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1572
1573 # in case we didn't source git-prompt.sh
1574 if ! declare -f __git_ps1 > /dev/null; then
1575 __git_ps1() {
1576 :
1577 }
1578 fi
1579
1580 # this needs to come before next ps1 stuff
1581 # this stuff needs bash 4, feb 2009,
1582 # old enough to no longer condition on $BASH_VERSION anymore
1583 shopt -s autocd
1584 shopt -s dirspell
1585 PS1='\w'
1586 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1587 PROMPT_DIRTRIM=2
1588 bind -m vi-command B:shell-backward-word
1589 bind -m vi-command W:shell-forward-word
1590 fi
1591
1592 if [[ $SSH_CLIENT ]]; then
1593 PS1="\h $PS1"
1594 fi
1595
1596 prompt_command() {
1597 local return=$? # this MUST COME FIRST
1598 local psc pst ps_char ps_color stale_subvol
1599 unset IFS
1600 history -a # save history
1601
1602 # for titlebar
1603 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1604 # from the screen man page
1605 if [[ $TERM == screen* ]]; then
1606 local title_escape="\033]..2;"
1607 else
1608 local title_escape="\033]0;"
1609 fi
1610 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1611 fi
1612
1613
1614 case $return in
1615 0) ps_color="$(get_term_color blue)"
1616 ps_char='\$'
1617 ;;
1618 1) ps_color="$(get_term_color green)"
1619 ps_char="$return \\$"
1620 ;;
1621 *) ps_color="$(get_term_color yellow)"
1622 ps_char="$return \\$"
1623 ;;
1624 esac
1625 if [[ ! -O . ]]; then # not owner
1626 if [[ -w . ]]; then # writable
1627 ps_color="$(get_term_color bold red)"
1628 else
1629 ps_color="$(get_term_color bold green)"
1630 fi
1631 fi
1632 # I would set nullglob, but bash has had bugs where that
1633 # doesn't work if not in top level.
1634 if [[ -e /nocow/btrfs-stale ]] && ((`ls -AUq /nocow/btrfs-stale|wc -l`)); then
1635 ps_char="! $ps_char"
1636 fi
1637 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1638 # emacs completion doesn't like the git prompt atm, so disabling it.
1639 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1640 }
1641 PROMPT_COMMAND=prompt_command
1642 fi
1643
1644
1645
1646 ###########################################
1647 # stuff that makes sense to be at the end #
1648 ###########################################
1649 if [[ "$SUDOD" ]]; then
1650 cd "$SUDOD"
1651 unset SUDOD
1652 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1653 cd /a
1654 fi
1655
1656
1657 # best practice
1658 unset IFS
1659
1660
1661 # if someone exported $SOE, catch errors
1662 if [[ $SOE ]]; then
1663 errcatch
1664 fi
1665
1666 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1667 # https://github.com/rubygems/rubygems/pull/1002
1668 # further problems: installing multi-user ruby and user ruby,
1669 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1670 # There a third hybrid form, which passenger error suggested I use,
1671 # but it didn't actually work.
1672
1673 # in cased I never need this
1674 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1675 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1676 # source $(rvm 1.9.3 do rvm env --path)
1677 #fi
1678
1679 # based on warning from rvmsudo
1680 export rvmsudo_secure_path=1
1681
1682 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1683 source "/usr/local/rvm/scripts/rvm"
1684 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1685 source $HOME/.rvm/scripts/rvm
1686 fi
1687
1688 export GOPATH=$HOME/go
1689 path_add $GOPATH/bin
1690
1691
1692 path_add --end ~/.npm-global
1693
1694
1695 # didn't get drush working, if I did, this seems like the
1696 # only good thing to include for it.
1697 # Include Drush completion.
1698 # if [ -f "/home/ian/.drush/drush.complete.sh" ] ; then
1699 # source /home/ian/.drush/drush.complete.sh
1700 # fi
1701
1702
1703 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1704 # i added an extra condition as gentoo xorg guide says depending on
1705 # $DISPLAY is fragile.
1706 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1707 exec startx
1708 fi
1709
1710
1711 # ensure no bad programs appending to this file will have an affect
1712 return 0