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