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