various fixes and improvements
[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 source /a/bin/log-once/log-once-function
208 path_add /a/exe
209 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
210 # todo, these need to be renamed to be less generic.
211 # sync overrode something else useful
212 #path_add $HOME/bin/bash-programs-by-ian/utils
213
214
215 ###############
216 ### aliases ###
217 ###############
218
219 # very few aliases, functions are always preferred.
220
221 # ancient stuff.
222 if [[ $OS == Windows_NT ]]; then
223 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
224 export DISPLAY=nt
225 alias j='command cygpath'
226 alias t='command cygstart'
227 alias cygstart='echo be quick, use the alias "t" instead :\)'
228 alias cygpath='echo be quick, use the alias "j" instead :\)'
229 fi
230
231
232
233 # keep this in mind? good for safety.
234 # alias cp='cp -i'
235 # alias mv='mv -i'
236
237
238 # remove any default aliases for these
239 unalias ls ll grep &>/dev/null ||:
240
241
242
243
244
245
246
247
248
249
250 #####################
251 ### functions ####
252 #####################
253
254
255
256
257 # file cut copy and paste, like the text buffers :)
258 # I havn't tested these.
259 _fbufferinit() { # internal use by
260 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
261 rm -rf "$my_f_tempdir"/*
262 }
263 fcp() { # file cp
264 _fbufferinit
265 cp "$@" "$my_f_tempdir"/
266 }
267 fct() { # file cut
268 _fbufferinit
269 mv "$@" "$my_f_tempdir"/
270 }
271 fpst() { # file paste
272 [[ $2 ]] && { echo too many arguments; return 1; }
273 target=${1:-.}
274 cp "$my_f_tempdir"/* "$target"
275 }
276
277
278 # todo, update this
279 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
280
281
282 _cdiff-prep() {
283 # join options which are continued to multiples lines onto one line
284 local first=true
285 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
286 # remove leading spaces/tabs. assumes extglob
287 if [[ $line == "[ ]*" ]]; then
288 line="${line##+( )}"
289 fi
290 if $first; then
291 pastline="$line"
292 first=false
293 elif [[ $line == *=* ]]; then
294 echo "$pastline" >> "$2"
295 pastline="$line"
296 else
297 pastline="$pastline $line"
298 fi
299 done
300 echo "$pastline" >> "$2"
301 }
302
303 _khfix_common() {
304 local h=${1##*@}
305 ssh-keygen -R $h
306 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
307 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
308 }
309 khfix() { # known hosts fix
310 _khfix_common "$@"
311 ssh $1 :
312 }
313 khcopy() {
314 _khfix_common "$@"
315 ssh-copy-id $1
316 }
317
318 a() {
319 beet "${@}"
320 }
321
322 ack() { ack-grep "$@"; }
323
324 bashrcpush () {
325 local startdir="$PWD"
326 cd ~
327 for x in "$@"; do
328 ssh $x mkdir -p bin/distro-functions/src
329 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
330 done
331 cd $(mktemp -d)
332 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
333 for x in "$@"; do
334 tar cz * | ssh $x tar xz
335 done
336 cd "$startdir"
337 }
338
339 caa() { git commit --amend --no-edit -a; }
340
341 calc() { echo "scale=3; $*" | bc -l; }
342 # no having to type quotes, but also no command history:
343 clc() {
344 local x
345 read -r x
346 echo "scale=3; $x" | bc -l
347 }
348
349 cam() {
350 git commit -am "$*"
351 }
352
353 ccat () { # config cat. see a config without extra lines.
354 grep '^\s*[^[:space:]#]' "$@"
355 }
356
357 cdiff() {
358 # diff config files,
359 # setup for format of postfix, eg:
360 # option = stuff[,]
361 # [more stuff]
362 local pastline
363 local unified="$(mktemp)"
364 local f1="$(mktemp)"
365 local f2="$(mktemp)"
366 _cdiff-prep "$1" "$f1"
367 _cdiff-prep "$2" "$f2"
368 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
369 while IFS= read -r line; do
370 # the default bright red / blue doesn't work in emacs shell
371 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
372 done < "$unified"
373 }
374
375 cgpl ()
376 {
377 if [[ $# == 0 ]]; then
378 cp /a/bin/data/COPYING .
379 else
380 cp /a/bin/data/COPYING "$@"
381 fi
382 }
383
384 chown() {
385 # makes it so chown -R symlink affects the symlink and its target.
386 if [[ $1 == -R ]]; then
387 shift
388 command chown -h "$@"
389 command chown -R "$@"
390 else
391 command chown "$@"
392 fi
393 }
394
395 cim() {
396 git commit -m "$*"
397 }
398
399 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 --follow-symlinks -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 pithos() {
749 cd /a/opt/Pithosfly/
750 python3 -m pithos&r
751 }
752
753 pakaraoke() {
754 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
755 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
756 }
757
758
759 pfind() { #find *$1* in $PATH
760 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
761 local pathArray
762 IFS=: pathArray=($PATH); unset IFS
763 find "${pathArray[@]}" -iname "*$1*"
764 }
765
766 pick-trash() {
767 # trash-restore lists everything that has been trashed at or below CWD
768 # This picks out files just in CWD, not subdirectories,
769 # which also match grep $1, usually use $1 for a time string
770 # which you get from running restore-trash once first
771 local name x ask
772 local nth=1
773 # last condition is to not ask again for ones we skipped
774 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
775 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
776 name="$(echo "$name" | head -n $nth | tail -n 1 )"
777 read -p "$name [Y/n] " ask
778 if [[ ! $ask || $ask == [Yy] ]]; then
779 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
780 echo $x | restore-trash > /dev/null
781 elif [[ $ask == [Nn] ]]; then
782 nth=$((nth+1))
783 else
784 return
785 fi
786 done
787 }
788
789 postconfin() {
790 local MAPFILE
791 mapfile -t
792 local s
793 [[ $EUID == 0 ]] || s=s
794 $s postconf -ev "${MAPFILE[@]}"
795 }
796
797 pub() {
798 rld /a/h/_site/ li:/var/www/iankelling.org/html
799 }
800
801 pubip() { curl -4s https://icanhazip.com; }
802 whatismyip() { pubip; }
803
804
805 pwgen() {
806 apg -s -m 10 -x 14 -t
807 }
808
809
810 q() { # start / launch a program in the backround and redir output to null
811 "$@" &> /dev/null &
812 }
813
814 r() {
815 exit "$@" 2>/dev/null
816 }
817
818 rbpipe() { rbt post -o --diff-filename=- "$@"; }
819 rbp() { rbt post -o "$@"; }
820
821 rl() {
822 # rsync, root is required to keep permissions right.
823 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
824 # --no-times --delete
825 # basically, make an exact copy, use checksums instead of file times to be more accurate
826 rsync -ahvic --delete "$@"
827 }
828 rld() {
829 # like rlu, but don't delete files on the target end which
830 # do not exist on the original end.
831 rsync -ahvic "$@"
832 }
833 complete -F _rsync -o nospace rld rl rlt
834
835 rlt() {
836 # rl without preserving modification time.
837 rsync -ahvic --delete --no-t "$@"
838 }
839
840 rlu() { # [OPTS] HOST PATH
841 # eg rlu -opts frodo testpath
842 # useful for selectively sending dirs which have been synced with unison,
843 # where the path is the same on both hosts.
844 opts=("${@:1:$#-2}") # 1 to last -2
845 path="${@:$#}" # last
846 host="${@:$#-1:1}" # last -1
847 if [[ $path == .* ]]; then echo error: need absolut path; return 1; fi
848 # rync here uses checksum instead of time so we don't mess with
849 # unison relying on time as much. g is for group, same reason
850 # to keep up with unison.
851 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
852 }
853
854
855 rspicy() { # HOST DOMAIN
856 local port=$(ssh $1<<EOF
857 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
858 sed -rn "s/.*port='([0-9]+).*/\1/p"
859 EOF
860 )
861 if [[ $port ]]; then
862 spicy -h $1 -p $port
863 else
864 echo "error: no port found. check that the domain is running."
865 fi
866 }
867
868 s() {
869 # background
870 # alias s='SUDOD="$PWD" sudo -i '
871 # because this is an alias, and the extra space at the end, it would allow
872 # aliases to be used with it. but aliases aren't used in scripts,
873 # better to eliminate inconsistencies. Plus, you can't do s=s; $s command
874 # with an alias, which I like to do in some functions
875 # extra space at the end allows aliases to work
876 #
877 # note: gksudo is recommended for X apps because it does not set the
878 # home directory to the same, and thus apps writing to ~ fuck things up
879 # with root owned files.
880 #
881 if [[ $EUID != 0 || $1 == -* ]]; then
882 SUDOD="$PWD" sudo -i "$@"
883 else
884 "$@"
885 fi
886 }
887
888 safe_rename() {
889 if [[ $# != 2 ]]; then
890 echo safe_rename error: $# args, need 2 >2
891 return 1
892 elif [[ $1 != $2 ]]; then
893 if [[ -e $2 ]]; then
894 echo Cannot rename "$1" to "$2" as it already exists.
895 else
896 mv "$1" "$2"
897 fi
898 fi
899 }
900
901
902 sb() { # sudo bash -c
903 # use sb instead of s is for sudo redirections,
904 # eg. sb 'echo "ok fine" > /etc/file'
905 local SUDOD="$PWD"
906 sudo -i bash -c "$@"
907 }
908 complete -F _root_command s sb
909
910
911 ser() {
912 local s; [[ $EUID != 0 ]] && s=sudo
913 if type -p systemctl &>/dev/null; then
914 $s systemctl $1 $2
915 else
916 $s service $2 $1
917 fi
918 }
919
920 sgo() { # service go
921 service=$1
922 ser restart $service
923 if type -p systemctl &>/dev/null; then
924 ser enable $service
925 fi
926 }
927
928
929 shellck() {
930 # 2086 = unquoted $var
931 # 2046 = unquoted $(cmd)
932 # i had -x as an arg, but debian testing(stretch) doesn't support it
933 shellcheck -e 2086,2046,2068,2006,2119 "$@"
934 }
935
936
937 slog() {
938 # log with script. timing is $1.t and script is $1.s
939 # -l to save to ~/typescripts/
940 # -t to add a timestamp to the filenames
941 local logdir do_stamp arg_base
942 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
943 logdir="/a/dt/"
944 do_stamp=false
945 while getopts "lt" option
946 do
947 case $option in
948 l ) arg_base=$logdir ;;
949 t ) do_stamp=true ;;
950 esac
951 done
952 shift $(($OPTIND - 1))
953 arg_base+=$1
954 [[ -e $logdir ]] || mkdir -p $logdir
955 $do_stamp && arg_base+=$(date +%F.%T%z)
956 script -t $arg_base.s 2> $arg_base.t
957 }
958 splay() { # script replay
959 #logRoot="$HOME/typescripts/"
960 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
961 scriptreplay "$1.t" "$1.s"
962 }
963
964 sr() {
965 # sudo redo. be aware, this command may not work right on strange distros or earlier software
966 if [[ $# == 0 ]]; then
967 sudo -E bash -c -l "$(history -p '!!')"
968 else
969 echo this command redos last history item. no argument is accepted
970 fi
971 }
972
973 srm () {
974 # with -ll, less secure but faster.
975 command srm -ll "$@"
976 }
977
978 srun() {
979 scp $2 $1:/tmp
980 ssh $1 /tmp/${2##*/} "${@:2}"
981 }
982
983 t() {
984 local x
985 local -a args
986 if type -t trash-put >/dev/null; then
987 # skip args that don't exist, or else it's an err
988 for x in "$@"; do [[ ! -e $x ]] || args+=("$x"); done
989 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
990 else
991 rm -rf "$@"
992 fi
993 }
994
995
996 tclock() {
997 clear
998 date +%l:%_M
999 len=60
1000 # this goes to full width
1001 #len=${1:-$((COLUMNS -7))}
1002 x=1
1003 while true; do
1004 if (( x == len )); then
1005 end=true
1006 d="$(date +%l:%_M) "
1007 else
1008 end=false
1009 d=$(date +%l:%M:%_S)
1010 fi
1011 echo -en "\r"
1012 echo -n "$d"
1013 for ((i=0; i<x; i++)); do
1014 if (( i % 6 )); then
1015 echo -n _
1016 else
1017 echo -n .
1018 fi
1019 done
1020 if $end; then
1021 echo
1022 x=1
1023 else
1024 x=$((x+1))
1025 fi
1026 sleep 5
1027 done
1028 }
1029
1030
1031 te() {
1032 # test existence / exists
1033 local ret=0
1034 for x in "$@"; do
1035 [[ -e "$x" || -L "$x" ]] || ret=1
1036 done
1037 return $ret
1038 }
1039
1040 tm() {
1041 # timer in minutes
1042 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1043 }
1044
1045 ts() { # start editing a new file
1046 [[ $# != 1 ]] && echo "I need a filename." && return 1
1047 local quiet
1048 if [[ $- != *i* ]]; then
1049 quiet=true
1050 fi
1051 if [[ $1 == *.c ]]; then
1052 e '#include <stdio.h>' >"$1"
1053 e '#include <stdlib.h>' >>"$1"
1054 e 'int main(int argc, char * argv[]) {' >>"$1"
1055 e ' printf( "hello world\n");' >>"$1"
1056 e ' return 0;' >>"$1"
1057 e '}' >>"$1"
1058 e "${1%.c}: $1" > Makefile
1059 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1060 e "#!/bin/bash" >run.sh
1061 e "./${1%.c}" >>run.sh
1062 chmod +x run.sh
1063 elif [[ $1 == *.java ]]; then
1064 e "public class ${1%.*} {" >"$1"
1065 e ' public static void main(String[] args) {' >>"$1"
1066 e ' System.out.println("Hello, world!");' >>"$1"
1067 e ' }' >>"$1"
1068 e '}' >>"$1"
1069 else
1070 echo "#!/bin/bash" > "$1"
1071 chmod +x "$1"
1072 fi
1073 [[ $quiet ]] || g "$1"
1074 }
1075
1076
1077 tu() {
1078 local s;
1079 local dir="$(dirname "$1")"
1080 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1081 s=s;
1082 fi
1083 $s teeu "$@"
1084 }
1085
1086 tx() { # toggle set -x, and the prompt so it doesn't spam
1087 if [[ $- == *x* ]]; then
1088 set +x
1089 PROMPT_COMMAND=prompt_command
1090 else
1091 unset PROMPT_COMMAND
1092 PS1="\w \$ "
1093 set -x
1094 fi
1095 }
1096
1097 vc() {
1098 [[ $1 ]] || { e "$0: error, expected cmd to run"; return 1; }
1099 # manually run vpn so it stays within a network namespace,
1100 # until I get it all wired up with systemd.
1101 newns vpn start
1102 pid=$(< /run/openvpn/client.pid)
1103 if [[ ! $pid ]]; then
1104 s ip netns exec vpn /usr/sbin/openvpn --daemon ovpn --config /etc/openvpn/client.conf --cd /etc/openvpn --writepid /run/openvpn/client.pid
1105 elif [[ ! -e /proc/$pid ]]; then
1106 echo "$0: ERROR: pidfile pid $pid is not a process!!!"
1107 return 1
1108 fi
1109 gksudo -- ip netns exec vpn gksudo -u ${SUDO_USER:-$USER} "$@"
1110 }
1111
1112 transmission() {
1113 vc transmission-gtk&
1114 i=0
1115 while ((i < 10)); do
1116 tun_ip=$(s ip netns exec vpn ip a show dev tun0 | sed -rn 's/^ *inet (10\.8\.\S+).*/\1/p')
1117 [[ ! $tun_ip ]] || break
1118 sleep 1
1119 done
1120 echo "$0: tun_ip=$tun_ip"
1121 [[ $tun_ip ]] || { e "$0: error: no tun0 addr found"; return 1; }
1122 ssh dopub bash <<EOF
1123 rule="-A PREROUTING -i eth0 -p tcp -m tcp --dport 63324 -j DNAT --to-destination $tun_ip:63324"
1124 found=false
1125 while read -r line; do
1126 if [[ \$line == \$rule ]] && ! \$found; then
1127 found=true
1128 else
1129 iptables -t nat -D \${line#-A}
1130 fi
1131 done < <(iptables -t nat -S | grep -E -- '--dport\s+63324')
1132 \$found || iptables -t nat \$rule
1133 EOF
1134 }
1135
1136 virshrm() {
1137 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1138 }
1139
1140 vm-set-listen(){
1141 local t=$(mktemp)
1142 local vm=$1
1143 local ip=$2
1144 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1145 sed -r "s/listen='[^']+/listen='$ip/"> $t
1146 s virsh undefine $vm
1147 s virsh define $t
1148 }
1149
1150
1151 vmshare() {
1152 vm-set-listen $1 0.0.0.0
1153 }
1154
1155
1156 vmunshare() {
1157 vm-set-listen $1 127.0.0.1
1158 }
1159
1160 vpn() {
1161 s systemctl start openvpn@client&
1162 journalctl --unit=openvpn@client -f -n0
1163 }
1164
1165
1166 vpnoff() {
1167 s systemctl stop openvpn@client
1168 }
1169
1170
1171 vrm() {
1172 virsh destroy $1
1173 virsh undefine $1
1174 }
1175
1176
1177
1178 vspicy() {
1179 # connect to vms made with virt-install
1180 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1181 sed -r "s/.*port='([0-9]+).*/\1/")
1182 }
1183
1184
1185 whatismyip() { curl ipecho.net/plain ; echo; }
1186
1187
1188 #############################
1189 ######### misc stuff ########
1190 #############################
1191
1192 if [[ $- == *i* ]]; then
1193 # commands to run when bash exits normally
1194 trap "hl; _smh" EXIT
1195 fi
1196
1197
1198 # temporary variables to test colorization
1199 # some copied from gentoo /etc/bash/bashrc,
1200 use_color=false
1201 # dircolors --print-database uses its own built-in database
1202 # instead of using /etc/DIR_COLORS. Try to use the external file
1203 # first to take advantage of user additions.
1204 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1205 match_lhs=""
1206 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1207 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1208 [[ -z ${match_lhs} ]] \
1209 && type -P dircolors >/dev/null \
1210 && match_lhs=$(dircolors --print-database)
1211 # test if our $TERM is in the TERM values in dircolor
1212 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1213
1214
1215 if ${use_color} && [[ $- == *i* ]]; then
1216
1217 if [[ $XTERM_VERSION == Cygwin* ]]; then
1218 get_term_color() {
1219 for x in "$@"; do
1220 case $x in
1221 underl) echo -n $'\E[4m' ;;
1222 bold) echo -n $'\E[1m' ;;
1223 red) echo -n $'\E[31m' ;;
1224 green) echo -n $'\E[32m' ;;
1225 blue) echo -n $'\E[34m' ;;
1226 cyan) echo -n $'\E[36m' ;;
1227 yellow) echo -n $'\E[33m' ;;
1228 purple) echo -n $'\E[35m' ;;
1229 nocolor) echo -n $'\E(B\E[m' ;;
1230 esac
1231 done
1232 }
1233
1234 else
1235 get_term_color() {
1236 for x in "$@"; do
1237 case $x in
1238 underl) echo -n $(tput smul) ;;
1239 bold) echo -n $(tput bold) ;;
1240 red) echo -n $(tput setaf 1) ;;
1241 green) echo -n $(tput setaf 2) ;;
1242 blue) echo -n $(tput setaf 4) ;;
1243 cyan) echo -n $(tput setaf 6) ;;
1244 yellow) echo -n $(tput setaf 3) ;;
1245 purple) echo -n $(tput setaf 5) ;;
1246 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1247 esac
1248 done
1249 }
1250 fi
1251 else
1252 get_term_color() {
1253 :
1254 }
1255 fi
1256 # Try to keep environment pollution down, EPA loves us.
1257 unset safe_term match_lhs use_color
1258
1259
1260
1261
1262
1263
1264 ###############
1265 # prompt ######
1266 ###############
1267
1268
1269 if [[ $- == *i* ]]; then
1270 # git branch/status prompt function
1271 if [[ $OS != Windows_NT ]]; then
1272 GIT_PS1_SHOWDIRTYSTATE=true
1273 fi
1274 # arch source lopip show -fcation
1275 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1276 # fedora/debian source
1277 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1278
1279 # in case we didn't source git-prompt.sh
1280 if ! declare -f __git_ps1 > /dev/null; then
1281 __git_ps1() {
1282 :
1283 }
1284 fi
1285
1286 # this needs to come before next ps1 stuff
1287 # this stuff needs bash 4, feb 2009,
1288 # old enough to no longer condition on $BASH_VERSION anymore
1289 shopt -s autocd
1290 shopt -s dirspell
1291 PS1='\w'
1292 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1293 PROMPT_DIRTRIM=2
1294 bind -m vi-command B:shell-backward-word
1295 bind -m vi-command W:shell-forward-word
1296 fi
1297
1298 if [[ $SSH_CLIENT ]]; then
1299 PS1="\h $PS1"
1300 fi
1301
1302 prompt_command() {
1303 local return=$? # this MUST COME FIRST
1304 local psc pst
1305 local ps_char ps_color
1306 unset IFS
1307 history -a # save history
1308 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1309 # from the screen man page
1310 if [[ $TERM == screen* ]]; then
1311 local title_escape="\033]..2;"
1312 else
1313 local title_escape="\033]0;"
1314 fi
1315 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1316 fi
1317
1318 case $return in
1319 0) ps_color="$(get_term_color blue)"
1320 ps_char='\$'
1321 ;;
1322 1) ps_color="$(get_term_color green)"
1323 ps_char="$return \\$"
1324 ;;
1325 *) ps_color="$(get_term_color yellow)"
1326 ps_char="$return \\$"
1327 ;;
1328 esac
1329 if [[ ! -O . ]]; then # not owner
1330 if [[ -w . ]]; then # writable
1331 ps_color="$(get_term_color bold red)"
1332 else
1333 ps_color="$(get_term_color bold green)"
1334 fi
1335 fi
1336 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1337 # emacs completion doesn't like the git prompt atm, so disabling it.
1338 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1339 }
1340 PROMPT_COMMAND=prompt_command
1341 fi
1342
1343
1344
1345
1346
1347 ###########################################
1348 # stuff that makes sense to be at the end #
1349 ###########################################
1350 if [[ "$SUDOD" ]]; then
1351 cd "$SUDOD"
1352 unset SUDOD
1353 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1354 cd /a
1355 fi
1356
1357
1358 # best practice
1359 unset IFS
1360
1361
1362 # if someone exported $SOE, catch errors
1363 if [[ $SOE ]]; then
1364 errcatch
1365 fi
1366
1367 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1368 # https://github.com/rubygems/rubygems/pull/1002
1369 # further problems: installing multi-user ruby and user ruby,
1370 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1371 # There a third hybrid form, which passenger error suggested I use,
1372 # but it didn't actually work.
1373
1374 # in cased I never need this
1375 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1376 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1377 # source $(rvm 1.9.3 do rvm env --path)
1378 #fi
1379
1380 # based on warning from rvmsudo
1381 export rvmsudo_secure_path=1
1382
1383 # for other script I wrote
1384 #export ACME_TINY_PATH=/a/opt/acme-tiny
1385 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1386
1387 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1388 source "/usr/local/rvm/scripts/rvm"
1389 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1390 source $HOME/.rvm/scripts/rvm
1391 fi
1392
1393
1394 path_add --end ~/.npm-global
1395
1396 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1397 # i added an extra condition as gentoo xorg guide says depending on
1398 # $DISPLAY is fragile.
1399 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1400 exec startx
1401 fi
1402 # ensure no bad programs appending to this file will have an affect
1403 return 0