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