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