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