minor bug fix
[distro-setup] / brc
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4 # this gets sourced. shebang is just for file mode detection
5
6 # note, to catch errors in functions but not outside, do:
7 # set -E -o pipefail
8 # trap return ERR
9 # trap 'trap ERR' RETURN
10
11
12 # * settings
13
14 CDPATH=.
15
16 set -o pipefail
17
18 # remove all aliases. aliases provided by the system tend to get in the way,
19 # for example, error happens if I try to define a function the same name as an alias
20 unalias -a
21
22 # remove gnome keyring warning messages
23 # there is probably a more proper way, but I didnt find any easily on google
24 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
25 #unset GNOME_KEYRING_CONTROL
26
27 # use extra globing features.
28 shopt -s extglob
29 # include .files when globbing, but ignore files name . and ..
30 # setting this also sets dotglob.
31 export GLOBIGNORE="*/.:*/.."
32
33 # broken with bash_completion package. Saw a bug for this once. dont anymore.
34 # still broken in wheezy
35 # still buggered in latest stable from the web, version 2.1
36 # perhaps its fixed in newer git version, which fails to make for me
37 # this note is from 6-2014.
38 # still broken in flidas.
39 #shopt -s nullglob
40
41 # make tab on an empty line do nothing
42 shopt -s no_empty_cmd_completion
43
44 # fix spelling errors for cd, only in interactive shell
45 shopt -s cdspell
46 # append history instead of overwritting it
47 shopt -s histappend
48 # for compatibility, per gentoo/debian bashrc
49 shopt -s checkwinsize
50 # attempt to save multiline single commands as single history entries.
51 shopt -s cmdhist
52 # enable **
53 shopt -s globstar
54
55
56 # inside emacs fixes
57 if [[ $RLC_INSIDE_EMACS ]]; then
58 # EMACS is used by bash on startup, but we dont need it anymore.
59 # plus I hit a bug in a makefile which inherited it
60 unset EMACS
61 export RLC_INSIDE_EMACS
62 export PAGER=cat
63 export MANPAGER=cat
64 # scp completion does not work, but this doesnt fix it. todo, figure this out
65 complete -r scp &> /dev/null
66 # todo, remote file completion fails, figure out how to turn it off
67 export NODE_DISABLE_COLORS=1
68 # This gets rid of ugly terminal escape chars in node repl
69 # sometime, Id like to have completion working in emacs shell for node
70 # the offending chars can be found in lib/readline.js,
71 # things that do like:
72 # stream.write('\x1b[' + (x + 1) + 'G');
73 # We can remove them and keep readline, for example by doing this
74 # to start a repl:
75 #!/usr/bin/env nodejs
76 # var readline = require('readline');
77 # readline.cursorTo = function(a,b,c) {};
78 # readline.clearScreenDown = function(a) {};
79 # const repl = require('repl');
80 # var replServer = repl.start('');
81 #
82 # no prompt, or else readline complete seems to be confused, based
83 # on our column being different? node probably needs to send
84 # different kind of escape sequence that is not ugly. Anyways,
85 # completion doesnt work yet even with the ugly prompt, so whatever
86 #
87 export NODE_NO_READLINE=1
88
89 fi
90
91 # emacs has a different default search path than the info command. This
92 # adds the info defaults to emacs, but not the reverse, because I dun
93 # care much about the cli. The search path is only on the cli if you run
94 # "info xxx", or in emacs if you run '(info xxx)', so not that
95 # important, but might as well fix it.
96
97 # info info says this path is what was compiled, and its not documented
98 # anywhere. Through source grepping, i found it in filesys.h of the info
99 # source in trisquel flidas.
100 #
101 # Traling : means for emacs to add its own stuff on to the end.
102
103 export INFOPATH=$PATH:/usr/local/info:/usr/info:/usr/local/lib/info:/usr/lib/info:/usr/local/gnu/info:/usr/local/gnu/lib/info:/usr/gnu/info:/usr/gnu/lib/info:/opt/gnu/info:/usr/share/info:/usr/share/lib/info:/usr/local/share/info:/usr/local/share/lib/info:/usr/gnu/lib/emacs/info:/usr/local/gnu/lib/emacs/info:/usr/local/lib/emacs/info:/usr/local/emacs/info:.:
104
105 if [[ $- == *i* ]]; then
106 # for readline-complete.el
107 if [[ $RLC_INSIDE_EMACS ]]; then
108 # all for readline-complete.el
109 stty echo
110 bind 'set horizontal-scroll-mode on'
111 bind 'set print-completions-horizontally on'
112 bind '"\C-i": self-insert'
113 else
114
115 if [[ $KONSOLE_PROFILE_NAME ]]; then
116 TERM=xterm-256color
117 fi
118
119 # todo: not sure this works in sakura
120 #stty werase undef
121 #bind "\C-w": kill-region
122 # sakura == xterm-256color
123 # konsole == xterm
124 if [[ $TERM == xterm* ]]; then
125 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
126 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
127 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
128 else
129 # make ctrl-backspace work. for konsole, i fixed it through
130 # /home/iank/.local/share/konsole/default.keytab
131 stty werase '^h'
132 bind '"\eOc": shell-forward-word'
133 bind '"\eOd": shell-backward-word'
134 fi
135 # i cant remember why i did this, probably to free up some keys to bind
136 # to other things in bash.
137 # other than C-c and C-z, the rest defined by stty -a are, at least in
138 # gnome-terminal, overridden by bash, or disabled by the system
139 stty lnext undef stop undef start undef
140 fi
141
142 fi
143
144
145 # history number. History expansion is good.
146 PS4='$LINENO+ '
147 # history file size limit, set to unlimited.
148 # this needs to be different from the default because
149 # default HISTFILESIZE is 500 and could clobber our history
150 HISTFILESIZE=
151 # max commands 1 session can append/read from history
152 HISTSIZE=1000000
153 # the time format display when doing the history command
154 # also, setting this makes the history file record time
155 # of each command as seconds from the epoch
156 HISTTIMEFORMAT="%Y-%m-%d %I:%M %p "
157 # consecutive duplicate lines dont go in history
158 HISTCONTROL=ignoredups
159 # works in addition to HISTCONTROL to do more flexible things
160 # it could also do the same things as HISTCONTROL and thus replace it,
161 # but meh. dunno why, but just " *" does glob expansion, so use [ ] to avoid it.
162 HISTIGNORE='pass *:[ ]*:otp *:oathtool *'
163
164 export BC_LINE_LENGTH=0
165
166 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
167
168 # note, if I use a machine I dont want files readable by all users, set
169 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
170
171 # i for insensitive. the rest from
172 # X means dont remove the current screenworth of output upon exit
173 # R means to show colors n things
174 export LESS=RXi
175 export SYSTEMD_LESS=$LESS
176
177
178 # * include files
179
180
181
182 # if someone exported $SOE (stop on error), catch errors.
183 #
184 # Note, on debian this results in the following warning when in ssh,
185 # hich I haven't figured out how to fix. It doesn't happen if we source
186 # after the shell has started
187 #
188 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
189 # bash: warning: cannot start debugger; debugging mode disabled
190 if [[ $SOE ]]; then
191 if [[ -e /a/bin/errhandle/err ]]; then
192 source /a/bin/errhandle/err
193 fi
194 fi
195
196 # based on readme.debian. dunno if this will break on other distros.
197 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
198 source /usr/share/wcd/wcd-include.sh
199 fi
200
201 if [[ -s /a/bin/small-misc-bash/ll-function ]]; then
202 # shellcheck source=/a/bin/small-misc-bash/ll-function
203 source /a/bin/small-misc-bash/ll-function
204 elif [[ -s ~/.iank/ll-function ]]; then
205 source ~/.iank/ll-function
206 fi
207
208 # * functions
209
210
211 ..() { c ..; }
212 ...() { c ../..; }
213 ....() { c ../../..; }
214 .....() { c ../../../..; }
215 ......() { c ../../../../..; }
216
217 # file cut copy and paste, like the text buffers :)
218 # I havnt tested these.
219 _fbufferinit() { # internal use
220 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
221 rm -rf "${my_f_tempdir:?}"/*
222 }
223 fcp() { # file cp
224 _fbufferinit
225 cp "$@" "$my_f_tempdir"/
226 }
227 fct() { # file cut
228 _fbufferinit
229 mv "$@" "$my_f_tempdir"/
230 }
231 fpst() { # file paste
232 [[ $2 ]] && { echo too many arguments; return 1; }
233 target=${1:-.}
234 cp "$my_f_tempdir"/* "$target"
235 }
236
237 _khfix_common() {
238 local host=${1##*@}
239 local ip port
240 read -r ip port < <(timeout 1 ssh -oBatchMode=yes -oControlMaster=no -oControlPath=/ -v $1 |& sed -rn "s/debug1: Connecting to $host \[([^\]*)] port ([0-9]+).*/\1 \2/p")
241 if [[ ! $ip ]]; then
242 echo "khfix: ssh failed"
243 return 1
244 fi
245 if [[ $port != 22 ]]; then
246 ip_entry="[$ip]:$port"
247 host_entry="[$host]:$port"
248 else
249 ip_entry=$ip
250 host_entry=$host
251 fi
252 ssh-keygen -R "$host_entry" -f $(readlink -f ~/.ssh/known_hosts)
253 echo "khfix: removing key for $ip_entry"
254 ssh-keygen -R "$ip_entry" -f $(readlink -f ~/.ssh/known_hosts)
255 }
256 khfix() { # known hosts fix
257 _khfix_common "$@" || return 1
258 ssh $1 :
259 }
260 khcopy() {
261 _khfix_common "$@"
262 ssh-copy-id $1
263 }
264
265 a() {
266 local x
267 x=$(readlink -nf "${1:-$PWD}")
268 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
269 echo -n "$x" | xclip -selection clipboard
270 echo -n "$x" | xclip
271 }
272
273 ack() { ack-grep "$@"; }
274
275 b() {
276 # backwards
277 c -
278 }
279
280
281 # c. better cd
282 if type -p wcd &>/dev/null; then
283 if [[ $RLC_INSIDE_EMACS ]]; then
284 c() { wcd -c -z 50 -o "$@"; }
285 else
286 # lets see what the fancy terminal does from time to time
287 c() { wcd -c -z 50 "$@"; }
288 fi
289 else
290 c() { cd "$@"; }
291 fi
292
293 c4() { c /var/log/exim4; }
294
295 caa() { git commit --amend --no-edit -a; }
296
297 caf() {
298 # shellcheck disable=SC2033
299 find -L $1 -type f -not \( -name .svn -prune -o -name .git -prune \
300 -o -name .hg -prune -o -name .editor-backups -prune \
301 -o -name .undo-tree-history -prune \) \
302 -exec bash -lc 'hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
303
304 }
305
306 calc() { echo "scale=3; $*" | bc -l; }
307 # no having to type quotes, but also no command history:
308 clc() {
309 local x
310 read -r x
311 echo "scale=3; $x" | bc -l
312 }
313
314 cam() {
315 git commit -am "$*"
316 }
317
318
319 ccat () { # config cat. see a config without extra lines.
320 grep '^\s*[^;[:space:]#]' "$@"
321 }
322
323
324 _cdiff-prep() {
325 # join options which are continued to multiples lines onto one line
326 local first=true
327 while IFS= read -r line; do
328 # remove leading spaces/tabs. assumes extglob
329 if [[ $line == "[ ]*" ]]; then
330 line="${line##+( )}"
331 fi
332 if $first; then
333 pastline="$line"
334 first=false
335 elif [[ $line == *=* ]]; then
336 echo "$pastline" >> "$2"
337 pastline="$line"
338 else
339 pastline="$pastline $line"
340 fi
341 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
342 echo "$pastline" >> "$2"
343 }
344
345 cdiff() {
346 # diff config files,
347 # setup for format of postfix, eg:
348 # option = stuff[,]
349 # [more stuff]
350 local pastline unified f1 f2
351 unified="$(mktemp)"
352 f1="$(mktemp)"
353 f2="$(mktemp)"
354 _cdiff-prep "$1" "$f1"
355 _cdiff-prep "$2" "$f2"
356 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
357 while IFS= read -r line; do
358 # the default bright red / blue doesnt work in emacs shell
359 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
360 done < "$unified"
361 }
362
363
364 cat-new-files() {
365 local start=$SECONDS
366 local dir="$1"
367 inotifywait -m "$dir" -e create -e moved_to |
368 # shellcheck disable=SC2030
369 while read -r filedir _ file; do
370 cat "$filedir$file"
371 hr
372 calc $((SECONDS - start)) / 60
373 sleep 5
374 done
375
376 }
377
378 # shellcheck disable=SC2032
379 chown() {
380 # makes it so chown -R symlink affects the symlink and its target.
381 if [[ $1 == -R ]]; then
382 shift
383 command chown -h "$@"
384 command chown -R "$@"
385 else
386 command chown "$@"
387 fi
388 }
389
390 cim() {
391 git commit -m "$*"
392 }
393
394 cl() {
395 # choose recent directory. cl = cd list
396 c =
397 }
398
399 d() { builtin bg; }
400 complete -A stopped -P '"%' -S '"' d
401
402
403 dc() {
404 diff --strip-trailing-cr -w "$@" # diff content
405 }
406
407 despace() {
408 local x y
409 for x in "$@"; do
410 y="${x// /_}"
411 safe_rename "$x" "$y"
412 done
413 }
414
415 dig() {
416 command dig +nostats +nocmd "$@"
417 }
418 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
419 digsort() {
420 local sec
421 sec=
422 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
423 if [[ $l == [^\;]* ]]; then
424 sec+="$l"$'\n'
425 else
426 if [[ $sec ]]; then
427 printf "%s" "$sec" | sort
428 sec=
429 fi
430 printf "%s\n" "$l"
431 fi
432 done
433 }
434 # compare digs to the 2 servers
435 # usage: digdiff @server1 @server2 DIG_ARGS
436 # note: only the soa master nameserver will respond with
437 # ra "recursive answer" flag. That difference is meaningless afaik.
438 digdiff() {
439 local s1 s2
440 s1=$1
441 shift
442 s2=$1
443 shift
444 digsort $s1 "$@" | tee /tmp/digdiff
445 diff -u /tmp/digdiff <(digsort $s2 "$@")
446 }
447
448 dt() {
449 date "+%A, %B %d, %r" "$@"
450 }
451
452 dus() { # du, sorted, default arg of
453 du -sh ${@:-*} | sort -h
454 }
455
456
457
458 e() { echo "$@"; }
459
460 # echo args
461 ea() {
462 if (( ! $# )); then
463 echo no args
464 fi
465 for arg; do
466 printf "%qEOL\n" "${arg}"
467 printf "%s" "${arg}" |& hexdump -C
468 done
469 }
470 # echo vars. print var including escapes, etc
471 ev() {
472 if (( ! $# )); then
473 echo no args
474 fi
475 for arg; do
476 printf "%qEOL\n" "${!arg}"
477 printf "%s" "${!arg}" |& hexdump -C
478 done
479 }
480
481
482 ediff() {
483 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
484 emacs --eval "(ediff-files \"$1\" \"$2\")"
485 }
486
487 # mail related
488 etail() {
489 tail -F /var/log/exim4/mainlog -n 200
490 }
491 eless() {
492 less /var/log/exim4/mainlog
493 }
494 eqcat() {
495 exiqgrep -i | while read i; do
496 exim -Mvh $i; hr; exim -Mvb $i; hr;
497 exigrep $i /var/log/exim4/mainlog; hr
498 done
499 }
500
501
502 # shellcheck disable=SC2032
503 f() {
504 # cd forward
505 c +
506 }
507
508 fa() {
509 # find array. make an array of file names found by find into $x
510 # argument: find arguments
511 # return: find results in an array $x
512 while read -rd ''; do
513 x+=("$REPLY");
514 done < <(find "$@" -print0);
515 }
516
517 faf() { # find all files. use -L to follow symlinks
518 find $@ -not \( -name .svn -prune -o -name .git -prune \
519 -o -name .hg -prune -o -name .editor-backups -prune \
520 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
521 }
522
523 # mail related
524 frozen() {
525 rm -rf /tmp/frozen
526 s mailq |gr frozen|awk '{print $3}' | while read -r id; do
527 s exim -Mvl $id
528 echo
529 s exim -Mvh $id
530 echo
531 s exim -Mvb $id
532 echo -e '\n\n##############################\n'
533 done | tee -a /tmp/frozen
534 }
535 frozenrm() {
536 local ids=()
537 while read -r line; do
538 printf '%s\n' "$line"
539 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
540 done < <(s mailq)
541 echo "sleeping for 2 in case you change your mind"
542 sleep 2
543 s exim -Mrm "${ids[@]}"
544 }
545
546 funce() {
547 # like -e for functions. returns on error.
548 # at the end of the function, disable with:
549 # trap ERR
550 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
551 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
552 trap ERR
553 return' ERR
554 }
555
556 getdir () {
557 local help="Usage: getdir [--help] PATH
558 Output the directory of PATH, or just PATH if it is a directory."
559 if [[ $1 == --help ]]; then
560 echo "$help"
561 return 0
562 fi
563 if [[ $# -ne 1 ]]; then
564 echo "getdir error: expected 1 argument, got $#"
565 return 1
566 fi
567 if [[ -d $1 ]]; then
568 echo "$1"
569 else
570 local dir
571 dir="$(dirname "$1")"
572 if [[ -d $dir ]]; then
573 echo "$dir"
574 else
575 echo "getdir error: directory does not exist"
576 return 1
577 fi
578 fi
579 }
580
581 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
582 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
583 local root
584 root=$(gitroot) || return 1 # function to set gitroot
585 builtin cd "$root"
586 git symbolic-ref HEAD refs/heads/$1
587 rm .git/index
588 git clean -fdx
589 }
590
591 # shellcheck disable=SC2120
592 gitroot() {
593 local help="Usage: gitroot [--help]
594 Print the full path to the root of the current git repo
595
596 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
597 and works in older versions of git which did not have that."
598 if [[ $1 == --help ]]; then
599 echo "$help"
600 return
601 fi
602 local p
603 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
604 [[ $p != /* ]] && p=$PWD
605 echo "${p%%/.git}"
606 }
607
608 gh() {
609 # i got an error, gh not found when doing a pull request, it seems like it wants itself in it\'s path.
610 local _oldpath="$PATH"
611 PATH="$PATH:$HOME/node_modules/.bin"
612 command gh "$@"
613 PATH="$_oldpath"
614 }
615
616 gmacs() {
617 # quit will prompt if the program crashes.
618 gdb -ex=r -ex=quit --args emacs "$@"; r;
619 }
620
621 gdkill() {
622 # kill the emacs daemon
623 pk1 emacs --daemon
624 }
625
626 gr() {
627 grep -iIP --color=auto "$@"
628 }
629
630 grr() { # grep recursive
631 if [[ ${#@} == 1 ]]; then
632 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" .
633 else
634 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@"
635 fi
636 }
637 rg() {
638 command rg -i -M 200 "$@"
639 }
640
641 hr() { # horizontal row. used to break up output
642 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq ${COLUMNS:-60})
643 echo
644 }
645
646 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
647
648 # get latest hub and run it
649 # main command to use:
650 # hub pull-request --no-edit
651 # --no-edit means to use the first commit\'s message as the pull request message.
652 # Also, you need to use a feature branch, not master in your fork.
653 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
654 # it\'s at ~/.config/hub
655 hub() {
656 local up uptar updir p
657 p=/github/hub/releases/
658 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
659 uptar=${up##*/}
660 updir=${uptar%.tgz}
661 if [[ ! -e /a/opt/$updir ]]; then
662 rm -rf /a/opt/hub-linux-amd64*
663 wget -P /a/opt $up
664 tar -C /a/opt -zxf /a/opt/$uptar
665 rm -f /a/opt/$uptar
666 s /a/opt/$updir/install
667 fi
668
669 # save token across computers
670 if [[ ! -L ~/.config/hub ]]; then
671 if [[ -e ~/.config/hub ]]; then
672 mv ~/.config/hub /p/c/subdir_files/.config/
673 fi
674 if [[ -e /p/c/subdir_files/.config/hub ]]; then
675 conflink
676 fi
677 fi
678 command hub "$@"
679 }
680
681 i() { git "$@"; }
682 # modified from ~/local/bin/git-completion.bash
683 # other completion commands are mostly taken from bash_completion package
684 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
685 || complete -o default -o nospace -F _git i
686
687 if ! type service &>/dev/null; then
688 service() {
689 echo actually running: systemctl $2 $1
690 systemctl $2 $1
691 }
692 fi
693
694
695
696 ic() {
697 # fast commit all
698 git commit -am "$*"
699 }
700
701
702
703 ifn() {
704 # insensitive find
705 find -L . -not \( -name .svn -prune -o -name .git -prune \
706 -o -name .hg -prune -o -name .editor-backups -prune \
707 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
708 }
709
710 ipdrop() {
711 s iptables -A INPUT -s $1 -j DROP
712 }
713
714
715 istext() {
716 grep -Il "" "$@" &>/dev/null
717 }
718
719 jtail() {
720 journalctl -n 10000 -f "$@"
721 }
722 jr() { journalctl "$@" ; }
723 jrf() { journalctl -f "$@" ; }
724
725 l() {
726 if [[ $PWD == /[iap] ]]; then
727 command ls -A --color=auto -I lost+found "$@"
728 else
729 command ls -A --color=auto "$@"
730 fi
731 }
732
733
734 lcn() { locate -i "*$**"; }
735
736 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first; }
737
738 lt() { ll -tr "$@"; }
739
740 lld() { ll -d "$@"; }
741
742 low() { # make filenames lowercase, remove bad chars
743 local f new
744 for f in "$@"; do
745 new="${f,,}" # downcase
746 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
747 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
748 new="${new%"${new##*[[:alnum:]]}"}"
749 # remove bad underscores, like __ and _._
750 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
751 safe_rename "$f" "$new" || return 1
752 done
753 return 0
754 }
755
756 lower() { # make first letter of filenames lowercase.
757 local x
758 for x in "$@"; do
759 if [[ ${x::1} == [A-Z] ]]; then
760 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
761 safe_rename "$x" "$y" || return 1
762 fi
763 done
764 }
765
766
767 k() { # history search
768 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80;
769 }
770
771 ks() { # history search
772 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq;
773 }
774
775
776 make-targets() {
777 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
778 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
779 }
780
781 mkc() {
782 mkdir "$1"
783 c "$1"
784 }
785
786 mkct() {
787 mkc $(mktemp -d)
788 }
789
790 mkt() { # mkdir and touch file
791 local path="$1"
792 mkdir -p "$(dirname "$path")"
793 touch "$path"
794 }
795
796 # shellcheck disable=SC2032
797 mkdir() { command mkdir -p "$@"; }
798
799 nopanic() {
800 # shellcheck disable=SC2024
801 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
802 }
803
804 p8() { ping 8.8.8.8; }
805 p6() { ping6 2001:4860:4860::8888; }
806
807 pkx() { # package extract
808 local pkg cached tmp f
809 c $(mktemp -d)
810 pkg=$1
811 # shellcheck disable=SC2012
812 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null)
813 if [[ $cached ]]; then
814 cp $cached .
815 else
816 aptitude download $pkg || return 1
817 fi
818 tmp=(*); f=${tmp[0]} # only 1 expected
819 ex $f
820 rm -f $f
821 }
822
823 # pgrep and kill
824 pk1() {
825 local pid
826 pid=($(pgrep -f "$*"))
827 case ${#pid[@]} in
828 1)
829 # shellcheck disable=SC2128
830 {
831 ps -F $pid
832 m kill $pid
833 }
834 ;;
835 0) echo "no pid found" ;;
836 *)
837 ps -F ${pid[@]}
838 ;;
839 esac
840 }
841
842 pubip() { curl -4s https://icanhazip.com; }
843 pubip6() { curl -6s https://icanhazip.com; }
844 whatismyip() { pubip; }
845
846 pwgen() {
847 # -m = min length
848 # -x = max length
849 # -t = print pronunciation
850 apg -m 14 -x 17 -t
851 for (( i=0; i<10; i++ )); do
852 shuf -n3 /usr/share/hunspell/en_US.dic | sed 's,/.*,,' | paste -sd . -
853
854 done
855 }
856
857 pwlong() {
858 # -M CLN = use Caps, Lowercase, Numbers
859 # -n 1 = 1 password
860 # -a 1 = use random instead of pronounceable algorithm
861 apg -m 50 -x 70 -n 1 -a 1 -M CLN
862 }
863
864
865 q() { # start / launch a program in the backround and redir output to null
866 "$@" &> /dev/null &
867 }
868
869 # shellcheck disable=SC2120
870 r() {
871 history -a # save history
872 exit ${1:0}
873 # i had this redir, not sure why
874 # exit "$@" 2>/dev/null
875 }
876
877 rl() {
878 # rsync, root is required to keep permissions right.
879 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
880 # --no-times --delete
881 # basically, make an exact copy, use checksums instead of file times to be more accurate
882 rsync -ahvic --delete "$@"
883 }
884 rld() {
885 # like rlu, but dont delete files on the target end which
886 # do not exist on the original end.
887 rsync -ahvic "$@"
888 }
889 complete -F _rsync -o nospace rld rl rlt
890
891 rlt() {
892 # rl without preserving modification time.
893 rsync -ahvic --delete --no-t "$@"
894 }
895
896 rlu() { # [OPTS] HOST PATH
897 # eg. rlu -opts frodo /testpath
898 # relative paths will expanded with readlink -f.
899 opts=("${@:1:$#-2}") # 1 to last -2
900 path="${*:$#}" # last
901 host="${*:$#-1:1}" # last -1
902 if [[ $path == .* ]]; then
903 path=$(readlink -f $path)
904 fi
905 # rync here uses checksum instead of time so we dont mess with
906 # unison relying on time as much. g is for group, same reason
907 # to keep up with unison.
908 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
909 }
910
911 rmstrips() {
912 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
913 }
914
915 s() {
916 # background
917 # I use a function because otherwise we cant use in a script,
918 # cant assign to variable.
919 #
920 # note: gksudo is recommended for X apps because it does not set the
921 # home directory to the same, and thus apps writing to ~ fuck things up
922 # with root owned files.
923 #
924 if [[ $EUID != 0 || $1 == -* ]]; then
925 SUDOD="$PWD" sudo -i "$@"
926 else
927 "$@"
928 fi
929 }
930
931 safe_rename() { # warn and dont rename if file exists.
932 # mv -n exists, but it\'s silent
933 if [[ $# != 2 ]]; then
934 echo safe_rename error: $# args, need 2 >2
935 return 1
936 fi
937 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
938 if [[ -e $2 || -L $2 ]]; then
939 echo "Cannot rename $1 to $2 as it already exists."
940 else
941 mv -vi "$1" "$2"
942 fi
943 fi
944 }
945
946
947 sb() { # sudo bash -c
948 # use sb instead of s is for sudo redirections,
949 # eg. sb 'echo "ok fine" > /etc/file'
950 local SUDOD="$PWD"
951 sudo -i bash -c "$@"
952 }
953 complete -F _root_command s sb
954
955
956 ser() {
957 local s; [[ $EUID != 0 ]] && s=s
958 if type -p systemctl &>/dev/null; then
959 $s systemctl $1 $2
960 else
961 $s service $2 $1
962 fi
963 }
964 # like restart, but do nothing if its not already started
965 srestart() {
966 local service=$1
967 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
968 systemctl restart $service
969 fi
970 }
971
972 setini() { # set a value in a .ini style file
973 key="$1" value="$2" section="$3" file="$4"
974 if [[ -s $file ]]; then
975 sed -ri -f - "$file" <<EOF
976 # remove existing keys
977 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
978 # add key
979 /^\s*\[$section\]/a $key=$value
980 # from section to eof, do nothing
981 /^\s*\[$section\]/,\$b
982 # on the last line, if we haven't found section yet, add section and key
983 \$a [$section]\\
984 $key=$value
985 EOF
986 else
987 cat >"$file" <<EOF
988 [$section]
989 $key=$value
990 EOF
991 fi
992 }
993
994 sgo() { # service go
995 service=$1
996 ser restart $service || return 1
997 if type -p systemctl &>/dev/null; then
998 ser enable $service
999 fi
1000 }
1001
1002 sgu() {
1003 systemctl list-unit-files | rg "$@"
1004 }
1005
1006
1007 sk() {
1008 # 2086: unquoted $var
1009 # 2046: unquoted $(cmd)
1010 # 2068: Double quote array expansions to avoid re-splitting elements.
1011 # 2119: Functions with optional args get bad warnings when none are passed.
1012 # 2033: too many false positives for thing that will never work, passing shell function to find.
1013 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1014 shellcheck -x -e 2086,2046,2068,2119,2033 "$@"
1015 # had this before. not sure what it is 2119
1016 }
1017
1018
1019 slog() {
1020 # log with script. timing is $1.t and script is $1.s
1021 # -l to save to ~/typescripts/
1022 # -t to add a timestamp to the filenames
1023 local logdir do_stamp arg_base
1024 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1025 logdir="/a/dt/"
1026 do_stamp=false
1027 while getopts "lt" option
1028 do
1029 case $option in
1030 l ) arg_base=$logdir ;;
1031 t ) do_stamp=true ;;
1032 esac
1033 done
1034 shift $((OPTIND - 1))
1035 arg_base+=$1
1036 [[ -e $logdir ]] || mkdir -p $logdir
1037 $do_stamp && arg_base+=$(date +%F.%T%z)
1038 script -t $arg_base.s 2> $arg_base.t
1039 }
1040 splay() { # script replay
1041 #logRoot="$HOME/typescripts/"
1042 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1043 scriptreplay "$1.t" "$1.s"
1044 }
1045
1046 sr() {
1047 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1048 if [[ $# == 0 ]]; then
1049 sudo -E bash -c -l "$(history -p '!!')"
1050 else
1051 echo this command redos last history item. no argument is accepted
1052 fi
1053 }
1054
1055 srm () {
1056 # with -ll, less secure but faster.
1057 command srm -ll "$@"
1058 }
1059
1060 srun() {
1061 scp $2 $1:/tmp
1062 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1063 }
1064
1065
1066 swap() {
1067 local tmp
1068 tmp=$(mktemp)
1069 mv $1 $tmp
1070 mv $2 $1
1071 mv $tmp $2
1072 }
1073
1074 tclock() { # terminal clock
1075 local x
1076 clear
1077 date +%l:%_M
1078 len=60
1079 # this goes to full width
1080 #len=${1:-$((COLUMNS -7))}
1081 x=1
1082 while true; do
1083 if (( x == len )); then
1084 end=true
1085 d="$(date +%l:%_M) "
1086 else
1087 end=false
1088 d=$(date +%l:%M:%_S)
1089 fi
1090 echo -en "\r"
1091 echo -n "$d"
1092 for ((i=0; i<x; i++)); do
1093 if (( i % 6 )); then
1094 echo -n _
1095 else
1096 echo -n .
1097 fi
1098 done
1099 if $end; then
1100 echo
1101 x=1
1102 else
1103 x=$((x+1))
1104 fi
1105 sleep 5
1106 done
1107 }
1108
1109
1110 te() {
1111 # test existence / exists
1112 local ret=0
1113 for x in "$@"; do
1114 [[ -e "$x" || -L "$x" ]] || ret=1
1115 done
1116 return $ret
1117 }
1118
1119
1120 tx() { # toggle set -x, and the prompt so it doesnt spam
1121 if [[ $- == *x* ]]; then
1122 set +x
1123 PROMPT_COMMAND=prompt-command
1124 # disabled due to issue on stretch, running ll we get error. something
1125 # about the DEBUG trap is broken
1126 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1127 # trap 'settitle "$BASH_COMMAND"' DEBUG
1128 # fi
1129 else
1130 # normally, i would just execute these commands in the function.
1131 # however, DEBUG is not inherited, so we need to run it outside a function.
1132 # And we want to run set -x afterwards to avoid spam, so we cram everything
1133 # in here, and then it will run after this function is done.
1134 #PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "; set -x'
1135
1136 unset PROMPT_COMMAND
1137 PS1="\w \$ "
1138 set -x
1139 fi
1140 }
1141
1142 psnetns() {
1143 # show all processes in the network namespace $1.
1144 # blank entries appear to be subprocesses/threads
1145 local x netns
1146 netns=$1
1147 ps -w | head -n 1
1148 s find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1149 while read -r l; do
1150 x=$(ps -w --no-headers -p $l);
1151 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1152 done
1153 }
1154
1155 m() { printf "%s\n" "$*"; "$@"; }
1156
1157
1158 virshrm() {
1159 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1160 }
1161
1162 vm-set-listen(){
1163 local t
1164 t=$(mktemp)
1165 local vm=$1
1166 local ip=$2
1167 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1168 sed -r "s/listen='[^']+/listen='$ip/"> $t
1169 s virsh undefine $vm
1170 s virsh define $t
1171 }
1172
1173
1174 vmshare() {
1175 vm-set-listen $1 0.0.0.0
1176 }
1177
1178
1179 vmunshare() {
1180 vm-set-listen $1 127.0.0.1
1181 }
1182
1183 # * misc stuff
1184
1185
1186 # temporary variables to test colorization
1187 # some copied from gentoo /etc/bash/bashrc,
1188 use_color=false
1189 # dircolors --print-database uses its own built-in database
1190 # instead of using /etc/DIR_COLORS. Try to use the external file
1191 # first to take advantage of user additions.
1192 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1193 match_lhs=""
1194 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1195 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1196 [[ -z ${match_lhs} ]] \
1197 && type -P dircolors >/dev/null \
1198 && match_lhs=$(dircolors --print-database)
1199 # test if our $TERM is in the TERM values in dircolor
1200 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1201
1202
1203 if ${use_color} && [[ $- == *i* ]]; then
1204
1205 term_bold="$(tput bold)"
1206 term_red="$(tput setaf 1)"
1207 term_green="$(tput setaf 2)"
1208 term_yellow="$(tput setaf 3)"
1209 term_purple="$(tput setaf 5)"
1210 term_nocolor="$(tput sgr0)" # no font attributes
1211
1212 # unused so far. commented for shellcheck
1213 # term_underl="$(tput smul)"
1214 # term_blue="$(tput setaf 4)"
1215 # term_cyan="$(tput setaf 6)"
1216
1217 fi
1218 # Try to keep environment pollution down, EPA loves us.
1219 unset safe_term match_lhs use_color
1220
1221 # * prompt
1222
1223
1224 if [[ $- == *i* ]]; then
1225
1226 # this needs to come before next ps1 stuff
1227 # this stuff needs bash 4, feb 2009,
1228 # old enough to no longer condition on $BASH_VERSION anymore
1229 shopt -s autocd
1230 shopt -s dirspell
1231 PS1='\w'
1232 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1233 PROMPT_DIRTRIM=2
1234 bind -m vi-command B:shell-backward-word
1235 bind -m vi-command W:shell-forward-word
1236 fi
1237
1238 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1239 PS1="\h $PS1"
1240 fi
1241
1242 # emacs terminal has problems if this runs slowly,
1243 # so I've thrown a bunch of things at the wall to speed it up.
1244 prompt-command() {
1245 local return=$? # this MUST COME FIRST
1246 local ps_char ps_color
1247 unset IFS
1248 history -a # save history
1249
1250 case $return in
1251 0) ps_color="$term_purple"
1252 ps_char='\$'
1253 ;;
1254 1) ps_color="$term_green"
1255 ps_char="$return \\$"
1256 ;;
1257 *) ps_color="$term_yellow"
1258 ps_char="$return \\$"
1259 ;;
1260 esac
1261 if [[ ! -O . ]]; then # not owner
1262 if [[ -w . ]]; then # writable
1263 ps_color="$term_bold$term_red"
1264 else
1265 ps_color="$term_bold$term_green"
1266 fi
1267 fi
1268
1269 # faster than sourceing the file im guessing
1270 if [[ -e /dev/shm/iank-status ]]; then
1271 eval $(< /dev/shm/iank-status)
1272 fi
1273 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1274 ps_char="@ $ps_char"
1275 fi
1276 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1277 }
1278 PROMPT_COMMAND=prompt-command
1279
1280 settitle () {
1281 if [[ $TERM == screen* ]]; then
1282 local title_escape="\033]..2;"
1283 else
1284 local title_escape="\033]0;"
1285 fi
1286 if [[ $0 != prompt-command ]]; then
1287 echo -ne "$title_escape$USER@$HOSTNAME ${PWD/#$HOME/~} "
1288 printf "%s" "$*"
1289 echo -ne "\007"
1290 fi
1291 }
1292
1293 # for titlebar.
1294 # condition from the screen man page i think.
1295 # note: duplicated in tx()
1296 # disabled. see note in tx
1297 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1298 # trap 'settitle "$BASH_COMMAND"' DEBUG
1299 # else
1300 # trap DEBUG
1301 # fi
1302
1303 fi
1304
1305 # * stuff that makes sense to be at the end
1306
1307
1308 # best practice
1309 unset IFS
1310
1311 # shellcheck disable=SC1090
1312 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
1313
1314
1315 # ensure no bad programs appending to this file will have an affect
1316 return 0