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