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