various updates
[distro-setup] / .bashrc
1 PATH="$PATH:/opt/midfin/common/lib"
2 # to debug
3 #set -x
4 # redirect output to log file
5 #exec 1>/a/tmp/bashlog
6 #exec 2>/a/tmp/bashlog
7
8
9 # By default this file is sourced for ALL ssh commands. This is wonky.
10 # Normally, this file is not sourced when a script is run, but we can override
11 # that by having #!/bin/bash -l.
12 # I want something similar for ssh commands. when a local script runs an ssh command,
13 # this file should not be sourced by default, but we should be able to override that.
14 #
15 # so here we test for conditions of a script under ssh and return if so. To test
16 # for an overriding condition, we have a few options. one is to use an
17 # environment variable. env variables sent across ssh are strictly limited. ssh
18 # -t which sets $SSH_TTY, but within a script that won't work because tty
19 # allocation will fail. We could override an obscure unused LC_var, like
20 # telephone, but I don't want to run into some edge case where that messes
21 # things up. we could transfer a file which we could test for, but I can't think
22 # of a way to make that inherently limited to a single ssh command. I choose to
23 # set SendEnv and AcceptEnv ssh config vars to allow the environment variable
24 # BASH_LOGIN_SHELL to propagate across ssh.
25
26 # assume we want ssh commands to source this file if we are sourcing it,
27 # and we haven't specified otherwise already
28 [[ ! $BASH_LOGIN_SHELL ]] && export BASH_LOGIN_SHELL=true
29
30 # first conditions show that we are an ssh command without an interactive shell
31 if [[ $SSH_CONNECTION ]] \
32 && [[ $- == *c* ]] \
33 && [[ ! $SSH_TTY ]] \
34 && [[ $- != *i* ]] \
35 && [[ ! $BASH_LOGIN_SHELL == true ]]; then
36 return
37 fi
38
39
40
41
42
43 ############
44 # settings #
45 ############
46
47 CDPATH=.
48
49 # remove all aliases. aliases provided by the system tend to get in the way,
50 # for example, error happens if I try to define a function the same name as an alias
51 unalias -a
52
53 # remove gnome keyring warning messages
54 # there is probably a more proper way, but I didn't find any easily on google
55 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
56 #unset GNOME_KEYRING_CONTROL
57
58 # use extra globing features.
59 shopt -s extglob
60 # include .files when globbing, but ignore files name . and ..
61 # setting this also sets dotglob
62 export GLOBIGNORE=*/.:*/..
63
64 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
65 # still broken in wheezy
66 # still buggered in latest stable from the web, version 2.1
67 # perhaps its fixed in newer git version, which fails to make for me
68 # this note is from 6-2014
69 #shopt -s nullglob
70
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
73
74 # advanced completion
75 # http://bash-completion.alioth.debian.org/
76 # might be sourced by the system already, but I've noticed it not being sourced before
77 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
78 . /usr/share/bash-completion/bash_completion
79 fi
80
81
82 # fix spelling errors for cd, only in interactive shell
83 shopt -s cdspell
84 # append history instead of overwritting it
85 shopt -s histappend
86 # for compatibility, per gentoo/debian bashrc
87 shopt -s checkwinsize
88 # attempt to save multiline single commands as single history entries.
89 shopt -s cmdhist
90 shopt -s globstar
91
92
93 # inside emacs fixes
94 if [[ $INSIDE_EMACS ]]; then
95 # EMACS is used by bash on startup, but we don't need it anymore.
96 # plus I hit a bug in a makefile which inherited it
97 unset EMACS
98 export INSIDE_EMACS
99 export PAGER=cat
100 export MANPAGER=cat
101 # scp completion does not work, but this doesn't fix it. todo, figure this out
102 complete -r scp &> /dev/null
103 # todo, remote file completion fails, figure out how to turn it off
104 fi
105
106
107 if [[ $- == *i* ]]; then
108 # for readline-complete.el
109 if [[ $INSIDE_EMACS ]]; then
110 # all for readline-complete.el
111 stty echo
112 bind 'set horizontal-scroll-mode on'
113 bind 'set print-completions-horizontally on'
114 bind '"\C-i": self-insert'
115 else
116 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
117 if [[ $TERM == "xterm" ]]; then
118 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
119 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
120 else
121 bind '"\eOc": shell-forward-word'
122 bind '"\eOd": shell-backward-word'
123 fi
124 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
125 # gnome-terminal, overridden by bash, or disabled by the system
126 stty werase undef lnext undef stop undef start undef
127
128 fi
129
130 fi
131
132
133 # history number. History expansion is good.
134 PS4='$LINENO+ '
135 # history file size limit, set to unlimited.
136 # this needs to be different from the default because
137 # default HISTFILESIZE is 500 and could clobber our history
138 HISTFILESIZE=
139 # max commands 1 session can append/read from history
140 HISTSIZE=100000
141 # my own history size limit based on lines
142 HISTFILELINES=1000000
143 HISTFILE=$HOME/.bh
144 # the time format display when doing the history command
145 # also, setting this makes the history file record time
146 # of each command as seconds from the epoch
147 HISTTIMEFORMAT="%I:%M %p %m/%d "
148 # consecutive duplicate lines don't go in history
149 HISTCONTROL=ignoredups
150 # works in addition to HISTCONTROL to do more flexible things
151 # it could also do the same things as HISTCONTROL and thus replace it,
152 # but meh
153 HISTIGNORE="k *"
154
155 export BC_LINE_LENGTH=0
156
157
158 # note, if I use a machine I don't want files readable by all users, set
159 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
160
161 C_DEFAULT_DIR=/a
162
163
164
165
166 ###################
167 ## include files ###
168 ###################
169
170 for _x in $HOME/bin/bash-programs-by-ian/repos/*/*-function ~/bin/distro-functions/src/*; do
171 source "$_x"
172 done
173 unset _x
174 source $HOME/bin/semi-private # so I can share my bashrc
175 source $HOME/path_add-function
176 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
177 path_add --ifexists --end /a/bin/sda/corpnext/cloudinit
178 # todo, these need to be renamed to be less generic.
179 # sync overrode something else useful
180 #path_add $HOME/bin/bash-programs-by-ian/utils
181 source $HOME/mw_vars
182
183 ###############
184 ### aliases ###
185 ###############
186
187 # disabled for now, but these are generally good
188 # if [[ $- == *i* ]]; then
189 # alias cp='cp -i'
190 # alias mv='mv -i'
191 # fi
192
193 # remove any default aliases for these
194 alias ls > /dev/null 2>&1 && unalias ls
195 alias ll > /dev/null 2>&1 && unalias ll
196 alias grep > /dev/null 2>&1 && unalias grep
197
198
199 mkdir() {
200 command mkdir -p "$@"
201 }
202
203
204 alias d='builtin bg'
205 complete -A stopped -P '"%' -S '"' d
206
207 alias hi='history'
208
209
210 # note: gksudo is recommended for X apps because it does not set the
211 # home directory to the same, and thus apps writing to ~ fuck things up
212 # with root owned files.
213
214 # background
215 # alias s='SUDOD="$PWD" sudo -i '
216 # because this is an alias, and the extra space at the end, it would allow
217 # aliases to be used with it. but aliases aren't used in scripts,
218 # better to eliminate inconsistencies. Plus, you can't do s=s; $s command
219 # with an alias, which I like to do in some functions
220 # extra space at the end allows aliases to work
221 s() {
222 if [[ $EUID != 0 || $1 == -* ]]; then
223 SUDOD="$PWD" sudo -i "$@"
224 else
225 "$@"
226 fi
227 }
228
229
230
231 if [[ $OS == Windows_NT ]]; then
232 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
233 export DISPLAY=nt
234 alias j='command cygpath'
235 alias t='command cygstart'
236 alias cygstart='echo be quick, use the alias "t" instead :\)'
237 alias cygpath='echo be quick, use the alias "j" instead :\)'
238
239 fi
240
241
242
243
244
245 #####################
246 ### functions ####
247 #####################
248
249
250
251 # netselect-apt finds a fast mirror.
252 # but we need to replace the mirrors ourselves,
253 # because it doesn't do that. best it can do is
254 # output a basic sources file
255 # here we get the server it found, get the main server we use
256 # then substitute all instances of one for the other in the sources file
257 # and backup original to /etc/apt/sources.list-original.
258 # this is idempotent
259 debian_pick_mirror () {
260 local x=$(mktemp -d)/f # safe way to get file name without creating one
261 sudo netselect-apt -o "$x" || return 1
262 x=$(_debian_pick_mirror_grep stable "$x")
263 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
264 sudo sed -i "s/$(_debian_pick_mirror_grep wheezy)/$x/" /etc/apt/sources.list
265 aptitude update
266 }
267
268 _debian_pick_mirror_grep () {
269 local x="$(grep -oP "^deb [^ ]+ $1 " ${2-/etc/apt/sources.list})"
270 x="${x#deb }"
271 x="${x% $1 }"
272 # replace / with \/ so we can use it with sed
273 echo "${x//\//\\/}"
274 }
275
276 # portable daemon, for debian & fedora
277 pdaemon () {
278 if isdeb; then
279 sudo /etc/init.d/$1 $2
280 else
281 sudo systemctl $2 $1.service
282 fi
283 }
284
285
286 a() {
287 beet "${@}"
288 }
289
290
291 t() {
292 trash-put "$@"
293 }
294
295
296 if type ack-grep >/dev/null 2>&1; then
297 alias ack=ack-grep
298 fi
299
300 postconfin() {
301 local MAPFILE
302 mapfile -t
303 local s
304 [[ $EUID == 0 ]] || s=s
305 $s postconf -v "${MAPFILE[@]}"
306 }
307
308 gr() {
309 grep -iI --color=auto "$@"
310 }
311
312 grr() {
313 grep -riI --color=auto "$@"
314 }
315
316 pub() {
317 rld /a/h/_site/ li:/var/www/iankelling.org/public_html
318 }
319
320 bashrcpush () {
321 local startdir="$PWD"
322 cd ~
323 for x in "$@"; do
324 ssh $x mkdir -p bin/distro-functions/src
325 tar cz bin/bash-programs-by-ian bin/semi-private bin/distro-functions/src | ssh $x tar xz
326 done
327 cd $(mktemp -d)
328 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
329 for x in "$@"; do
330 tar cz * | ssh $x tar xz
331 done
332 cd "$startdir"
333 }
334
335 whatismyip() { curl ipecho.net/plain ; echo; }
336
337 # history search
338 k() { grep -P "$@" ${HISTFILE:-~/.bash_history} | tail -n 40; }
339
340 calc() { echo "scale=3; $*" | bc -l; }
341
342 # diff config files,
343 # setup for format of postfix
344 # option = stuff[,]
345 # [more stuff]
346 cdiff() {
347
348 local pastline
349 local unified="$(mktemp)"
350 local f1="$(mktemp)"
351 local f2="$(mktemp)"
352
353 _cdiff-prep "$1" "$f1"
354 _cdiff-prep "$2" "$f2"
355 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
356 while IFS= read -r line; do
357 # the default bright red / blue doesn't work in emacs shell
358 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
359 done < "$unified"
360 }
361
362
363 # join options which are continued to multiples lines onto one line
364 _cdiff-prep() {
365 local first=true
366 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
367 # remove leading spaces/tabs. assumes extglob
368 if [[ $line == "[ ]*" ]]; then
369 line="${line##+( )}"
370 fi
371 if $first; then
372 pastline="$line"
373 first=false
374 elif [[ $line == *=* ]]; then
375 echo "$pastline" >> "$2"
376 pastline="$line"
377 else
378 pastline="$pastline $line"
379 fi
380 done
381 echo "$pastline" >> "$2"
382 }
383
384 # makes it so chown -R symlink affects the symlink and its target.
385 chown() {
386 if [[ $1 == -R ]]; then
387 shift
388 command chown -h "$@"
389 command chown "$@"
390 command chown -RH "$@"
391 else
392 command chown "$@"
393 fi
394 }
395
396
397
398 cgpl ()
399 {
400 if [[ $# == 0 ]]; then
401 cp /a/bin/data/COPYING .
402 else
403 cp /a/bin/data/COPYING "$@"
404 fi
405 }
406
407
408 dc() {
409 diff --strip-trailing-cr -w "$@" # diff content
410 }
411
412
413 dt() {
414 date "+%A, %B %d, %r" "$@"
415 }
416
417
418 e() { echo "$@"; }
419
420
421 envload() { # load environment from a previous: export > file
422 local file=${1:-$HOME/.${USER}_env}
423 eval "$(export | sed 's/^declare -x/export -n/')"
424 while IFS= read -r line; do
425 # declare -x makes variables local to a function
426 eval ${line/#declare -x/export}
427 done < "$file"
428 }
429
430
431
432 # havn't tested these:
433 #file cut copy and paste, like the text buffers :)
434 _fbufferinit() { # internal use by
435 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
436 rm -rf "$my_f_tempdir"/*
437 }
438 fcp() { # file cp
439 _fbufferinit
440 cp "$@" "$my_f_tempdir"/
441 }
442 fct() { # file cut
443 _fbufferinit
444 mv "$@" "$my_f_tempdir"/
445 }
446 fpst() { # file paste
447 [[ $2 ]] && { echo too many arguments; return 1; }
448 target=${1:-.}
449 cp "$my_f_tempdir"/* "$target"
450 }
451
452
453 # find array. make an array of file names found by find into $x
454 # argument: find arguments
455 # return: find results in an array $x
456 fa() {
457 while read -rd ''; do
458 x+=("$REPLY");
459 done < <(find "$@" -print0);
460 }
461
462
463 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
464 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
465 local gitroot
466 gitroot || return 1 # function to set gitroot
467 builtin cd "$gitroot"
468 git symbolic-ref HEAD refs/heads/$1
469 rm .git/index
470 git clean -fdx
471 }
472
473
474 ff() {
475 if type -P firefox &>/dev/null; then
476 firefox "$@"
477 else
478 iceweasel "$@"
479 fi
480 }
481
482 fw() {
483 firefox -P default "$@" >/dev/null 2>&1
484 }
485
486 fn() {
487 firefox -P alt "$@" >/dev/null 2>&1
488 }
489
490
491
492
493
494 # horizontal row. used to break up output
495 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
496
497
498 i() {
499 git "$@"
500 }
501 # modified from ~/local/bin/git-completion.bash
502 # other completion commands are mostly taken from bash_completion package
503 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
504 || complete -o default -o nospace -F _git i
505
506 # fast commit all
507 ic() {
508 git commit -am "$*"
509 }
510
511 # insensitive find
512 ifn () {
513 find . -iname '*'"$*"'*'
514 }
515
516
517
518
519 l() {
520 if [[ $PWD == /[iap] ]]; then
521 command ls -A --color=auto -I lost+found "$@"
522 else
523 command ls -A --color=auto "$@"
524 fi
525 }
526
527
528
529 lld() { ll -d "$@"; }
530
531
532 low() { # make filenames all lowercase
533 local x y
534 for x in "$@"; do
535 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
536 [[ $y != $x ]] && mv "$x" "$y"
537 done
538 }
539
540
541 lower() { # make first letter of filenames lowercase.
542 local x
543 for x in "$@"; do
544 if [[ ${x::1} == [A-Z] ]]; then
545 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
546 safe_rename "$x" "$y"
547 fi
548 done
549 }
550
551 safe_rename() {
552 if [[ $# != 2 ]]; then
553 echo safe_rename error: $# args, need 2 >2
554 return 1
555 elif [[ $1 != $2 ]]; then
556 if [[ -e $2 ]]; then
557 echo Cannot rename "$1" to "$2" as it already exists.
558 else
559 mv "$1" "$2"
560 fi
561 fi
562 }
563
564 despace() {
565 local x y
566 for x in "$@"; do
567 y="${x// /_}"
568 safe_rename "$x" "$y"
569 done
570 }
571
572
573
574
575
576 # test existence / exists
577 te() {
578 local ret=0
579 for x in "$@"; do
580 [[ -e "$x" || -L "$x" ]] || ret=1
581 done
582 return $ret
583 }
584
585 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
586 make-targets() {
587 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
588 }
589
590
591 # fix root file ownership for FILE argument.
592 # check if parent or grandparent is not root and if the dir of FILE is also
593 # owned by that user, and change ownership to that user
594 perm_fix() {
595 local parent
596 if [[ $EUID == 0 ]]; then
597 te "$1" || touch "$1"
598 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
599 argdir=$(getdir "$1")
600 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
601 if ! chown "--reference=$argdir" "$1"; then
602 echo failed to fix bad ownership file permissons
603 return 1
604 fi
605 fi
606 fi
607 fi
608 }
609
610 # see notes for usage
611 fsdiff () {
612 local missing=false
613 local dname="${PWD##*/}"
614 local m="/a/tmp/$dname-missing"
615 local d="/a/tmp/$dname-diff"
616 [[ -e $d ]] && rm "$d"
617 [[ -e $m ]] && rm "$m"
618 local msize=0
619 local fsfile
620 while read -r line; do
621 fsfile="$1${line#.}"
622 if [[ -e "$fsfile" ]]; then
623 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
624 else
625 missing=true
626 echo "$line" >> "$m"
627 msize=$((msize + 1))
628 fi
629 done < <(find -type f )
630 if $missing; then
631 echo "$m"
632 (( msize <= 100 )) && cat $m
633 fi
634 }
635
636 fsdiff-test() {
637 cd $(mktemp -d)
638 echo ok > a
639 echo nok > b
640 mkdir c
641 echo ok > c/d
642 local x=$(mktemp -d)
643 mkdir $x/c
644 echo different > $x/c/d
645 echo ok > $x/a
646 fsdiff $x
647 }
648 # expected output, with different tmp dirs
649 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
650 # /a/tmp/tmp.qLDkYxBYPM-missing
651 # ./b
652
653
654 # test whether missing files were renamed, generally for use with fsdiff
655 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
656 # echos non-renamed files
657 rename-test() {
658 local x y found
659 unset sums
660 for x in "$2"/*; do
661 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
662 done
663 while read -r line; do
664 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
665 renamed=false
666 for x in "${sums[@]}"; do
667 if [[ $missing_sum == "$x" ]]; then
668 renamed=true
669 break
670 fi
671 done
672 $renamed || echo "$line"
673 done < "$1"
674 return 0
675 }
676
677
678 # get a random string
679 #par2rbase=$(head -c 50 /dev/urandom | tr -cd '[:alpha:]')
680 par2r() {
681 [[ $par2rbase ]] || { echo "set \$par2rbase first"; return 1; }
682 d="$PWD"
683 for x in **; do
684 if [[ -d $x ]]; then
685 cd "$x"
686 par2 c QDLDeDJ6z4.par2 *
687 cd "$d"
688 fi
689 done
690
691 }
692
693 md5diff() {
694 [[ $(md5sum < "$1") != $(md5sum < "$2") ]]
695 }
696
697
698 pfind() { #find *$1* in $PATH
699 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
700 local pathArray
701 IFS=: pathArray=($PATH); unset IFS
702 find "${pathArray[@]}" -iname "*$1*"
703 }
704
705 # do pwd + some other info.
706 #pwd() { echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"; }
707
708
709 pwgen() { # generate a random password, with digits & punctuation and without
710 arg=${1:-50}
711 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
712 echo
713 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
714 head -c 5 /dev/urandom | tr -cd '[:alpha:]' | head -c "$arg"
715 echo
716 }
717
718 q() { # start / launch a program in the backround and redir output to null
719 "$@" &> /dev/null &
720 }
721
722
723
724 r() {
725 exit "$@" 2>/dev/null
726 }
727
728 # trash-restore lists everything that has been trashed at or below CWD
729 # This picks out files just in CWD, not subdirectories,
730 # which also match grep $1, usually use $1 for a time string
731 # which you get from running restore-trash once first
732 pick-trash() {
733 local name x ask
734 local nth=1
735 # last condition is to not ask again for ones we skipped
736 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
737 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
738 name="$(echo "$name" | head -n $nth | tail -n 1 )"
739 read -p "$name [Y/n] " ask
740 if [[ ! $ask || $ask == [Yy] ]]; then
741 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
742 echo $x | restore-trash > /dev/null
743 elif [[ $ask == [Nn] ]]; then
744 nth=$((nth+1))
745 else
746 return
747 fi
748 done
749 }
750
751 # rsync, root is required to keep permissions right.
752 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
753 # --no-times --delete
754 # basically, make an exact copy, use checksums instead of file times to be more accurate
755 rl() { rsync -ahvic --delete "$@"; }
756 # don't delete files on the target end which do not exist on the original end:
757 rld() { rsync -ahvic "$@"; }
758 complete -F _rsync -o nospace rld rlt fl
759 # rl without preserving modification time. for some reason I had this as default before.
760 # perhaps that reason will come up again and I will document it.
761 rlt() { rsync -ahvic --delete --no-t "$@"; }
762
763
764
765 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
766 sb() {
767 local SUDOD="$PWD"
768 sudo -i bash -c "$@"
769 }
770 complete -F _root_command s sb
771
772 # use -ll, less secure but faster.
773 srm () {
774 command srm -ll "$@"
775 }
776
777 # sudo redo. be aware, this command may not work right on strange distros or earlier software
778 sr() {
779 if [[ $# == 0 ]]; then
780 sudo -E bash -c -l "$(history -p '!!')"
781 else
782 echo this command redos last history item. no argument is accepted
783 fi
784 }
785
786 rbpipe() { rbt post -o --diff-filename=- "$@"; }
787 rbp() { rbt post -o "$@"; }
788
789
790 # log with script. timing is $1.t and script is $1.s
791 # -l to save to ~/typescripts/
792 # -t to add a timestamp to the filenames
793 slog() {
794 local logdir do_stamp arg_base
795 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
796 logdir="/a/dt/"
797 do_stamp=false
798 while getopts "lt" option
799 do
800 case $option in
801 l ) arg_base=$logdir ;;
802 t ) do_stamp=true ;;
803 esac
804 done
805 shift $(($OPTIND - 1))
806 arg_base+=$1
807 [[ -e $logdir ]] || mkdir -p $logdir
808 $do_stamp && arg_base+=$(date +%F.%T%z)
809 script -t $arg_base.s 2> $arg_base.t
810 }
811 splay() { # script replay
812 #logRoot="$HOME/typescripts/"
813 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
814 scriptreplay "$1.t" "$1.s"
815 }
816
817
818 # like -e for functions. returns on error.
819 # at the end of the function, disable with:
820 # trap ERR
821 funce() {
822 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
823 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
824 trap ERR
825 return' ERR
826 }
827
828 # timer in minutes
829 tm() {
830 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
831 }
832
833
834 myunison() {
835 s unison -auto -owner -group
836 }
837
838 tu() {
839 local s;
840 local dir="$(dirname "$1")"
841 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
842 s=s;
843 fi
844 $s teeu "$@"
845 }
846 ts() { # start editing a new file
847 [[ $# != 1 ]] && echo "I need a filename." && return 1
848 local quiet
849 if [[ $- != *i* ]]; then
850 quiet=true
851 fi
852 if [[ $1 == *.c ]]; then
853 e '#include <stdio.h>' >"$1"
854 e '#include <stdlib.h>' >>"$1"
855 e 'int main(int argc, char * argv[]) {' >>"$1"
856 e ' printf( "hello world\n");' >>"$1"
857 e ' return 0;' >>"$1"
858 e '}' >>"$1"
859 e "${1%.c}: $1" > Makefile
860 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
861 e "#!/bin/bash" >run.sh
862 e "./${1%.c}" >>run.sh
863 chmod +x run.sh
864 elif [[ $1 == *.java ]]; then
865 e "public class ${1%.*} {" >"$1"
866 e ' public static void main(String[] args) {' >>"$1"
867 e ' System.out.println("Hello, world!");' >>"$1"
868 e ' }' >>"$1"
869 e '}' >>"$1"
870
871 else
872 echo "#!/bin/bash" > "$1"
873 chmod +x "$1"
874 fi
875 [[ $quiet ]] || g "$1"
876
877 }
878
879 tx() { # toggle set -x, and the prompt so it doesn't spam
880 if [[ $- == *x* ]]; then
881 set +x
882 PROMPT_COMMAND=prompt_command
883 else
884 unset PROMPT_COMMAND
885 PS1="\w \$ "
886 set -x
887 fi
888 }
889
890
891
892
893 if [[ $OS == Windows_NT ]]; then
894 # cygstart wrapper
895 cs() {
896 cygstart "$@" &
897 }
898 xp() {
899 explorer.exe .
900 }
901 # launch
902 o() {
903 local x=(*$1*)
904 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
905 cygstart *$1* &
906 }
907 else
908 o() {
909 if type gvfs-open &> /dev/null ; then
910 gvfs-open "$@"
911 else
912 xdg-open "$@"
913 fi
914 # another alternative is run-mailcap
915 }
916 fi
917
918
919
920
921 # todo, update this
922 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
923
924
925
926 hl() { # history limit. Write extra history to archive file.
927 local max_lines linecount tempfile prune_lines x
928 local harchive="${HISTFILE}_archive"
929 for x in "$HISTFILE" "$harchive"; do
930 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
931 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
932 echo "error in hl: history file \$x:$x no good"
933 return 1
934 fi
935 done
936 history -a # save history
937 max_lines=$HISTFILELINES
938 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
939 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
940 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
941 if (($linecount > $max_lines)); then
942 prune_lines=$(($linecount - $max_lines))
943 head -n $prune_lines "$HISTFILE" >> "$harchive" \
944 && sed -ie "1,${prune_lines}d" $HISTFILE
945 fi
946 }
947
948 ############## work stuff #############
949
950 rn() {
951 pushd /sdx/test/sandbox/;
952 ./setup.sh;
953 ./run.sh;
954 popd
955 }
956
957 vrm() {
958 virsh destroy $1
959 virsh undefine $1
960 }
961
962
963
964
965 ############# some other section
966 if [[ $- == *i* ]]; then
967 # commands to run when bash exits normally
968 trap "hl; _smh" EXIT
969 fi
970
971
972 # temporary variables to test colorization
973 # some copied from gentoo /etc/bash/bashrc,
974 use_color=false
975 # dircolors --print-database uses its own built-in database
976 # instead of using /etc/DIR_COLORS. Try to use the external file
977 # first to take advantage of user additions.
978 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
979 match_lhs=""
980 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
981 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
982 [[ -z ${match_lhs} ]] \
983 && type -P dircolors >/dev/null \
984 && match_lhs=$(dircolors --print-database)
985 # test if our $TERM is in the TERM values in dircolor
986 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
987
988
989 if ${use_color} && [[ $- == *i* ]]; then
990
991 if [[ $XTERM_VERSION == Cygwin* ]]; then
992 get_term_color() {
993 for x in "$@"; do
994 case $x in
995 underl) echo -n $'\E[4m' ;;
996 bold) echo -n $'\E[1m' ;;
997 red) echo -n $'\E[31m' ;;
998 green) echo -n $'\E[32m' ;;
999 blue) echo -n $'\E[34m' ;;
1000 cyan) echo -n $'\E[36m' ;;
1001 yellow) echo -n $'\E[33m' ;;
1002 purple) echo -n $'\E[35m' ;;
1003 nocolor) echo -n $'\E(B\E[m' ;;
1004 esac
1005 done
1006 }
1007
1008 else
1009 get_term_color() {
1010 for x in "$@"; do
1011 case $x in
1012 underl) echo -n $(tput smul) ;;
1013 bold) echo -n $(tput bold) ;;
1014 red) echo -n $(tput setaf 1) ;;
1015 green) echo -n $(tput setaf 2) ;;
1016 blue) echo -n $(tput setaf 4) ;;
1017 cyan) echo -n $(tput setaf 6) ;;
1018 yellow) echo -n $(tput setaf 3) ;;
1019 purple) echo -n $(tput setaf 5) ;;
1020 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1021 esac
1022 done
1023 }
1024 fi
1025 else
1026 get_term_color() {
1027 :
1028 }
1029 fi
1030 # Try to keep environment pollution down, EPA loves us.
1031 unset safe_term match_lhs use_color
1032
1033
1034
1035
1036
1037
1038 ###############
1039 # prompt ######
1040 ###############
1041
1042
1043 if [[ $- == *i* ]]; then
1044 # git branch/status prompt function
1045 if [[ $OS != Windows_NT ]]; then
1046 GIT_PS1_SHOWDIRTYSTATE=true
1047 fi
1048 # arch source location
1049 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1050 # fedora/debian source
1051 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1052
1053 # in case we didn't source git-prompt.sh
1054 if ! declare -f __git_ps1 > /dev/null; then
1055 __git_ps1() {
1056 :
1057 }
1058 fi
1059
1060 # this needs to come before next ps1 stuff
1061 # this stuff needs bash 4, feb 2009,
1062 # old enough to no longer condition on $BASH_VERSION anymore
1063 shopt -s autocd
1064 shopt -s dirspell
1065 PS1='\w'
1066 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1067 PROMPT_DIRTRIM=2
1068 bind -m vi-command B:shell-backward-word
1069 bind -m vi-command W:shell-forward-word
1070 fi
1071
1072 if [[ $SSH_CLIENT ]]; then
1073 PS1="\h $PS1"
1074 fi
1075
1076 prompt_command() {
1077 local return=$? # this MUST COME FIRST
1078 local psc pst
1079 local ps_char ps_color
1080 unset IFS
1081 history -a # save history
1082 history -n # read any new history
1083 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1084 # from the screen man page
1085 if [[ $TERM == screen* ]]; then
1086 local title_escape="\033]..2;"
1087 else
1088 local title_escape="\033]0;"
1089 fi
1090 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1091 fi
1092
1093 case $return in
1094 0) ps_color="$(get_term_color blue)"
1095 ps_char='\$'
1096 ;;
1097 1) ps_color="$(get_term_color green)"
1098 ps_char="$return \\$"
1099 ;;
1100 *) ps_color="$(get_term_color yellow)"
1101 ps_char="$return \\$"
1102 ;;
1103 esac
1104 if [[ ! -O . ]]; then # not owner
1105 if [[ -w . ]]; then # writable
1106 ps_color="$(get_term_color bold red)"
1107 else
1108 ps_color="$(get_term_color bold green)"
1109 fi
1110 fi
1111 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1112 }
1113 PROMPT_COMMAND=prompt_command
1114 fi
1115
1116
1117
1118
1119
1120 ###########################################
1121 # stuff that makes sense to be at the end #
1122 ###########################################
1123 if [[ "$SUDOD" ]]; then
1124 cd "$SUDOD"
1125 unset SUDOD
1126 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1127 cd /a
1128 fi
1129
1130
1131 # best practice
1132 unset IFS
1133
1134
1135 # if someone exported $SOE, catch errors
1136 if [[ $SOE ]]; then
1137 errcatch
1138 fi
1139
1140 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1141 # https://github.com/rubygems/rubygems/pull/1002
1142 # further problems: installing multi-user ruby and user ruby,
1143 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1144 # There a third hybrid form, which passenger error suggested I use,
1145 # but it didn't actually work.
1146
1147 # in cased I never need this
1148 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1149 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1150 # source $(rvm 1.9.3 do rvm env --path)
1151 #fi
1152
1153 # based on warning from rvmsudo
1154 export rvmsudo_secure_path=1
1155
1156 if [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
1157 source "/usr/local/rvm/scripts/rvm"
1158 fi
1159 # make our last exit code be 0
1160 true