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