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
6 # Use source ~/.bashrc instead of doing bash -l when running a script
7 # so this can set extdebug and avoid the bash debugger.
10 if [[ -s /a
/bin
/bash-bear-trap
/bash-bear
]]; then
11 # shellcheck source=/a/bin/bash-bear-trap/bash-bear
12 source /a
/bin
/bash-bear-trap
/bash-bear
13 # wtf, shellcheck doesn't allow disabling warnings in elifs
15 # bleh shellcheck can't handle disabling in an elif, so nesting this if.
16 # shellcheck disable=SC2154 # set in .bashrc
17 if [[ -s $bashrc_dir/bash-bear
]]; then
18 # shellcheck source=/a/bin/bash-bear-trap/bash-bear
19 source $bashrc_dir/bash-bear
23 # In t8, it runs clear_console for login shells by default. I don't want
24 # my console cleared. And linux ttys get cleared without this.
25 if shopt login_shell
>/dev
/null
&& [[ -e ~
/.bash_logout
]]; then
29 # if [[ -s /usr/share/bash-completion/completions/git ]]; then
30 # source /usr/share/bash-completion/completions/git
32 # if [[ -s /usr/share/bash-completion/completions/gitk ]]; then
33 # source /usr/share/bash-completion/completions/gitk
36 # for testing error catching:
52 # remove all aliases. aliases provided by the system tend to get in the way,
53 # for example, error happens if I try to define a function the same name as an alias
56 # remove gnome keyring warning messages
57 # there is probably a more proper way, but I didnt find any easily on google
58 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
59 #unset GNOME_KEYRING_CONTROL
61 # use extra globing features.
63 # include .files when globbing, but ignore files name . and ..
64 # setting this also sets dotglob.
65 export GLOBIGNORE
="*/.:*/.."
67 # Useful info. see man bash.
71 # broken with bash_completion package. Saw a bug for this once. dont anymore.
72 # still broken in wheezy
73 # still buggered in latest stable from the web, version 2.1
74 # perhaps its fixed in newer git version, which fails to make for me
75 # this note is from 6-2014.
76 # still broken in flidas.
79 # make tab on an empty line do nothing
80 shopt -s no_empty_cmd_completion
82 # fix spelling errors for cd, only in interactive shell
84 # append history instead of overwritting it
86 # for compatibility, per gentoo/debian bashrc
88 # attempt to save multiline single commands as single history entries.
95 if [[ $LC_INSIDE_EMACS ]]; then
96 # EMACS is used by bash on startup, but we dont need it anymore.
97 # plus I hit a bug in a makefile which inherited it
99 export LC_INSIDE_EMACS
102 # scp completion does not work, but this doesnt fix it. todo, figure this out
103 #complete -r scp &> /dev/null
104 # todo, remote file completion fails, figure out how to turn it off
105 export NODE_DISABLE_COLORS
=1
106 # This gets rid of ugly terminal escape chars in node repl
107 # sometime, Id like to have completion working in emacs shell for node
108 # the offending chars can be found in lib/readline.js,
109 # things that do like:
110 # stream.write('\x1b[' + (x + 1) + 'G');
111 # We can remove them and keep readline, for example by doing this
113 #!/usr/bin/env nodejs
114 # var readline = require('readline');
115 # readline.cursorTo = function(a,b,c) {};
116 # readline.clearScreenDown = function(a) {};
117 # const repl = require('repl');
118 # var replServer = repl.start('');
120 # no prompt, or else readline complete seems to be confused, based
121 # on our column being different? node probably needs to send
122 # different kind of escape sequence that is not ugly. Anyways,
123 # completion doesnt work yet even with the ugly prompt, so whatever
125 export NODE_NO_READLINE
=1
129 export SSH_CONFIG_FILE_OVERRIDE
=/root
/.ssh
/confighome
131 # emacs has a different default search path than the info command. This
132 # adds the info defaults to emacs, but not the reverse, because I dun
133 # care much about the cli. The search path is only on the cli if you run
134 # "info xxx", or in emacs if you run '(info xxx)', so not that
135 # important, but might as well fix it.
137 # info info says this path is what was compiled, and its not documented
138 # anywhere. Through source grepping, i found it in filesys.h of the info
139 # source in trisquel flidas.
141 # Traling : means for emacs to add its own stuff on to the end.
143 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
:.
:
145 # for openwrt system that has no stty, this is easier than
146 # guarding every time i use it.
147 if ! type -p stty
>/dev
/null
; then
153 if [[ $
- == *i
* ]]; then
154 # for readline-complete.el
155 if [[ $LC_INSIDE_EMACS ]]; then
156 # all for readline-complete.el
158 bind 'set horizontal-scroll-mode on'
159 bind 'set print-completions-horizontally on'
160 bind '"\C-i": self-insert'
164 if [[ $TERM != dumb
]] && test -t 1; then
168 if [[ $KONSOLE_PROFILE_NAME ]]; then
172 if [[ $TERM == alacritty
&& ! -e /usr
/share
/terminfo
/a
/alacritty
]]; then
173 # todo: we should try installing the alacritty terminfo if it is not found
174 # https://github.com/alacritty/alacritty/issues/2838
178 # copying from the alacritty example above,
179 if [[ $TERM == xterm-kitty
]]; then
180 if [[ ! -e /usr
/share
/terminfo
/x
/xterm-kitty
]]; then
183 if [[ -e /a
/opt
/kitty
/shell-integration
/bash
/kitty.bash
]]; then
184 KITTY_SHELL_INTEGRATION
=t
185 source /a
/opt
/kitty
/shell-integration
/bash
/kitty.bash
190 # todo: not sure this works in sakura
192 #bind "\C-w": kill-region
193 # sakura == xterm-256color
195 if [[ $TERM != xterm-kitty
&& $TERM == xterm
* ]]; then
196 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
197 bind '"\e[1;5C": shell-forward-word' 2>/dev
/null
198 bind '"\e[1;5D": shell-backward-word' 2>/dev
/null
200 # make ctrl-backspace work. for konsole, i fixed it through
201 # /home/iank/.local/share/konsole/default.keytab
203 bind '"\eOc": shell-forward-word'
204 bind '"\eOd": shell-backward-word'
206 # i cant remember why i did this, probably to free up some keys to bind
207 # to other things in bash.
208 # other than C-c and C-z, the rest defined by stty -a are, at least in
209 # gnome-terminal, overridden by bash, or disabled by the system
210 stty lnext undef stop undef start undef
216 # fixup broken backspace in chroots
217 xterm-kitty|alacritty
)
219 TERM
=xterm-256color
command chroot
"$@"
224 export BC_LINE_LENGTH
=0
227 export PROFILE_TASKS_TASK_OUTPUT_LIMIT
=100
229 # note, if I use a machine I dont want files readable by all users, set
230 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
232 # i for insensitive. the rest from
233 # X means dont remove the current screenworth of output upon exit
234 # R means to show colors n things
235 # a useful flag is -F aka --quit-if-one-screen
237 export SYSTEMD_LESS
=$LESS
239 export NNN_COLORS
=2136
241 export SL_FILES_DIR
=/b
/ds
/sl
/.iank
242 export SL_INFO_DIR
=/p
/sshinfo
247 # this is adapted from things printed to term after install
248 # pyenv. commented for now since I'm not actually using pyenv.
250 # export PYENV_ROOT="$HOME/.pyenv"
251 # command -v pyenv &>/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
252 # command -v pyenv &>/dev/null && eval "$(pyenv init -)"
255 # output showed this example for pyenv-virtualenv, which i have no idea
256 # what it is, but leaving it as a comment in case I end up doing python
259 #eval "$(pyenv virtualenv-init -)"
260 ### end begin pyenv ###
266 if [[ -s $bashrc_dir/path-add-function
]]; then
267 source $bashrc_dir/path-add-function
268 if [[ $SSH_CLIENT ]]; then
269 if grep -qF /home
/iank
/.iank
/e
/e
/etc
/exports
&>/dev
/null
; then
270 export EMACSDIR
=/home
/iank
/.iank
/e
/e
276 # if someone exported $SOE (stop on error), catch errors.
278 # Note, on debian this results in the following warning when in ssh,
279 # hich I haven't figured out how to fix. It doesn't happen if we source
280 # after the shell has started
282 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
283 # bash: warning: cannot start debugger; debugging mode disabled
285 if [[ -e /a
/bin
/bash-bear-trap
/bash-bear
]]; then
286 source /a
/bin
/bash-bear-trap
/bash-bear
296 if [[ -s $path ]]; then
297 # shellcheck disable=SC1090 # this is dynamic, shellcheck can't follow it.
299 elif [[ -s $bashrc_dir/$file ]]; then
300 # shellcheck disable=SC1090 # this is dynamic, shellcheck can't follow it.
301 source $bashrc_dir/$file
306 mysrc
/a
/bin
/small-misc-bash
/ll-function
307 mysrc
/a
/bin
/distro-functions
/src
/package-manager-abstractions
309 # things to remember:
310 # ALT-C - cd into the selected directory
311 # CTRL-T - Paste the selected file path into the command line
313 # good guide to some of its basic features is the readme file
314 # https://github.com/junegunn/fzf
316 # if [[ -s /usr/share/doc/fzf/examples/key-bindings.bash ]]; then
317 # source /usr/share/doc/fzf/examples/key-bindings.bash
323 # temporary functions
325 m
"${@//spring/fall}"
328 e
"${@//spring/fall}"
332 ### begin FSF section ###
334 # Comments before functions are meant to be good useful
335 # documentation. If they fail at that, please improve them or send Ian a
338 ## copy bash completion
340 # It copies how the bash completion works from one command to other
341 # commands. Generally just use within a .bashrc.
343 # Usage: ORIGINAL_COMMAND TARGET_COMMAND...
349 if ! c
=$
(complete
-p $src 2>/dev
/null
); then
350 _completion_loader
$src &>/dev
/null ||
:
351 c
=$
(complete
-p $src 2>/dev
/null
) ||
return 0
359 ## BEGIN functions to change directory better than cd ##
363 # c: acts like cd, but stores directory history: you could alias to cd if you wanted.
366 # cl: list recent directories and optionally choose one.
368 # Finer details you may want to skip:
370 # bl: print the list of back and forward directories.
372 # We keep 2 stacks of directories, forward and back. Unlike with a web
373 # browser, the forward stack is not erased when going somewhere new.
375 # Recent directories are stored in ~/.cdirs.
377 declare -a _dir_forward _dir_back
379 # normally, the top of _dir_back is our current dir. if it isn't,
380 # put it on there, except we don't want to do that when we
381 # just launched a shell
382 if [[ $OLDPWD ]]; then
383 if (( ${#_dir_back[@]} == 0 )) ||
[[ ${_dir_back[-1]} != "$PWD" ]]; then
388 if (( ${#_dir_back[@]} == 0 )) ||
[[ ${_dir_back[-1]} != "$PWD" ]]; then
391 echo "$PWD" >> ~
/.cdirs
398 if (( ${#_dir_back[@]} == 0 )); then
399 echo "nothing left to go back to" >&2
402 top_back
="${_dir_back[-1]}"
404 if [[ $top_back == "$PWD" ]] && (( ${#_dir_back[@]} == 1 )); then
405 echo "already on last back entry" >&2
410 if [[ $top_back == "$PWD" ]]; then
411 # add to dirf if not already there
412 if (( ${#_dir_forward[@]} == 0 )) ||
[[ ${_dir_forward[-1]} != "$top_back" ]]; then
413 _dir_forward
+=("$top_back")
415 unset "_dir_back[-1]"
416 command cd "${_dir_back[-1]}"
418 if (( ${#_dir_forward[@]} == 0 )) ||
[[ ${_dir_forward[-1]} != "$PWD" ]]; then
419 _dir_forward
+=("$PWD")
421 command cd "$top_back"
424 # Interesting feature, not sure I want it.
425 # give us a peek at what is next in the list
426 # if (( ${#_dir_back[@]} >= 2 )); then
427 # printf "%s\n" "${_dir_back[-2]}"
431 # c/b/f Implementation notes:
433 # The top of the back is $PWD
434 # as long as the last directory change was due to c,b,or cl.
436 # Example of stack changes:
462 if (( ${#_dir_forward[@]} == 0 )); then
463 echo "no forward dir left" >&2
466 top_forward
="${_dir_forward[-1]}"
467 unset "_dir_forward[-1]"
470 # give us a peek at what is next in the list
471 # if (( ${#_dir_forward[@]} )); then
472 # printf "%s\n" "${_dir_forward[-1]}"
477 local i line input start
478 local -A buttondirs alines
479 local -a buttons
dirs lines
480 buttons
=( {a..z
} {2.
.9} )
481 if [[ ! -s ~
/.cdirs
]]; then
482 echo nothing
in ~
/.cdirs
488 mapfile
-t lines
<~
/.cdirs
489 start
=$
(( ${#lines[@]} - 1 ))
491 # we have ~33 buttons as of this writing, so lets
492 # prune down the history every once in a while.
493 if (( start
> 500 )); then
494 tac ~
/.cdirs |
awk '!seen[$0]++' |
head -n 200 |
tac | sponge ~
/.cdirs ||
[[ $?
== 141 ]]
497 for (( j
=start
; j
>= 0; j--
)); do
499 if [[ ! $line ||
${alines[$line]} ||
! -d "$line" ||
$line == "$PWD" || line
== "$HOME" ]]; then
503 buttondirs
[${buttons[i]}]="$line"
504 printf "%s %s\n" ${buttons[i]} "$line"
505 # the LINES bit is for when we have a short terminal, just dont print all
506 # the directories. alternative would be to do something like less the list.
507 if (( i
== ${#buttons[@]} - 1 )) ||
{ [[ $LINES ]] && (( i
== LINES
- 3 )); }; then
513 if (( i
== 0 )); then
514 echo "no dirs in ~/.cdirs"
518 if [[ $input != $
'\n' ]]; then
519 c
"${buttondirs[$input]}"
522 # bl = back list. lists the back and forward directories. i tend to
523 # forget this exists and use cl instead.
527 start
=$
(( ${#_dir_back[@]} - 1 ))
529 # cleanup possible repeating of pwd
530 if (( start
>= 0 )) && [[ ${_dir_back[$start]} == "$PWD" ]]; then
531 start
=$
(( start
- 1 ))
534 if (( start
>= 0 )); then
535 for (( i
=start
; i
>= 0 ; i--
)); do
536 printf "%s %s\n" $j ${_dir_back[i]}
538 if (( j
>= max
)); then
545 start
=$
(( ${#_dir_forward[@]} - 1 ))
547 # cleanup possible repeating of pwd
548 if (( start
>= 0 )) && [[ ${_dir_forward[$start]} == "$PWD" ]]; then
549 start
=$
(( start
- 1 ))
551 if (( start
< 0 )); then
556 for (( i
=start
; i
>= 0 ; i--
)); do
557 printf "%s %s\n" $j ${_dir_forward[i]}
559 if (( j
>= max
)); then
564 # like running cl <enter> a <enter>
567 mapfile
-t lines
<~
/.cdirs
568 start
=$
(( ${#lines[@]} - 1 ))
569 for (( j
=start
; j
>= 0; j--
)); do
571 if [[ ! $line ||
! -d "$line" ||
$line == "$PWD" || line
== "$HOME" ]]; then
579 ## END functions to change directory better than cd ##
581 # pee do. run args as a command with output copied to syslog.
583 # Usage: pd [-t TAG] COMMAND...
585 # -t TAG Override the tag in the syslog. The default is COMMAND with
586 # any path part is removed, eg. for /bin/cat the tag is cat.
588 # You can view the log via "journalctl -t TAG"
594 -t) tag
="$2"; shift 2 ;;
596 echo "PWD=$PWD command: $*" | logger
-t $tag
597 "$@" |
& pee
cat "logger -t $tag" || ret
=$?
598 echo "exited with status=$ret" | pee
cat "logger -t $tag"
599 # this avoids any err-catch
600 (( ret
== 0 )) ||
return $ret
604 # jdo = journal do. Run command as transient systemd service, tailing
605 # its output in the journal until it completes.
607 # Usage: jdo COMMAND...
609 # Compared to pd: commands recognize this is a non-interactive shell.
610 # The service is unaffected if our ssh connection dies, no need to run
613 # Note: The last few lines of any existing entries for a unit by that
614 # name will be output first, and there will be a few second delay at the
615 # start of the command, and a second or so at the end.
617 # Note: Functions and aliases obviously won't work, we resolve the
620 # Note: requires running as root.
622 local cmd cmd_name jr_pid ret
626 if [[ $EUID != 0 ]]; then
627 echo "jdo: error: rerun as root"
631 if [[ $cmd != /* ]]; then
632 cmd
=$
(type -P "$cmd")
635 journalctl
-qn2 -f -u "$cmd_name" &
636 # Trial and error of time needed to avoid missing initial lines.
637 # .5 was not reliable. 1 was not reliable. 2 was not reliable
640 systemd-run
--unit "$cmd_name" --wait --collect "$cmd" "$@" || ret
=$?
641 # The sleep lets the journal output its last line
642 # before the prompt comes up.
644 kill $jr_pid &>/dev
/null ||
:
647 # this avoids any err-catch
648 (( ret
== 0 )) ||
return $ret
656 ....
() { c ..
/..
/..
; }
657 .....
() { c ..
/..
/..
/..
; }
658 ......
() { c ..
/..
/..
/..
/..
; }
663 path
=$
(readlink
-e "$f")
664 echo "cat >$path <<'EOF'"
671 # file cut copy and paste, like the text buffers :)
672 # I havnt tested these.
673 _fbufferinit
() { # internal use
674 ! [[ $my_f_tempdir ]] && my_f_tempdir
="$(mktemp -d)"
675 rm -rf "${my_f_tempdir:?}"/*
679 cp "$@" "$my_f_tempdir"/
683 mv "$@" "$my_f_tempdir"/
685 fpst
() { # file paste
686 [[ $2 ]] && { echo too many arguments
; return 1; }
688 cp "$my_f_tempdir"/* "$target"
692 local host ip port
file key
693 read -r host ip port
< <(timeout
-s 9 2 ssh -oBatchMode=yes -oControlMaster=no
-oControlPath=/ -v $1 |
& sed -rn "s/debug1: Connecting to ([^ ]+) \[([^\]*)] port ([0-9]+).*/\1 \2 \3/p" ||
: )
694 file=$
(readlink
-f ~
/.ssh
/known_hosts
)
696 echo "khfix: ssh failed"
699 if [[ $port != 22 ]]; then
700 ip_entry
="[$ip]:$port"
701 host_entry
="[$host]:$port"
706 if [[ $host != "$ip" ]]; then
707 key
=$
(ssh-keygen
-F "$host_entry" -f $file |
sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
709 grep -Fv "$key" "$file" | sponge
"$file"
712 key
=$
(ssh-keygen
-F "$ip_entry" -f $file |
sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
714 grep -Fv "$key" "$file" | sponge
"$file"
716 ll ~
/.ssh
/known_hosts
719 khfix
() { # known hosts fix
720 _khfix_common
"$@" ||
return 1
728 # copy path into clipboard
731 x
=$
(readlink
-nf "${1:-$PWD}")
732 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
733 echo -n "$x" | xclip
-selection clipboard
737 # a1 = awk {print $1}
738 for field
in {1.
.20}; do
739 eval a
$field"() { awk '{print \$$field}'; }"
742 for num
in {1.
.9}; do
743 eval h
$num"() { head -n$num || [[ \$? == 141 ]]; }"
748 # shellcheck disable=SC2046 disable=SC2001 disable=SC2183 # hacks, expected
749 printf '%d.%d.%d.%d\n' $
(echo $1 |
sed 's/../0x& /g')
753 local f out outdir
in fname origdir skip1
757 while [[ $1 == -* ]]; do
759 # if we got interrupted after 1st phase
771 # first pass only uses about 1 cpu, so run in parallel
775 if [[ $f == /* ]]; then
780 out
="$origdir/$outdir/$fname"
781 mkdir
-p /tmp
/vp
9/$fname
783 if ! $skip1 && [[ ! -s ffmpeg2pass-0.log
]]; then
784 # -nostdin or else wait causes ffmpeg to go into stopped state. dunno why, random stackoverflow answer.
785 m ffmpeg
-nostdin -hide_banner -loglevel error
-i $in -g 192 -vcodec libvpx-vp9
-vf scale
=-1:720 -max_muxing_queue_size 9999 -b:v
750K
-pass 1 -an -f null
/dev
/null
787 if [[ -e $out ]]; then rm -f $out; fi
788 m ffmpeg
-nostdin -hide_banner -loglevel error
-y -i $in -g 192 -vcodec libvpx-vp9
-tile-rows 2 -vf scale
=-1:720 -max_muxing_queue_size 9999 -b:v
750K
-pass 2 -c:a libvorbis
-qscale:a
5 $out
795 utcl
() { # utc 24 hour time to local hour 24 hour time
796 echo "print( ($1 $(date +%z | sed -r 's/..$//;s/^(-?)0*/\1/')) % 24)"|python3
804 # for running in a fai rescue. iank specific.
806 d
=vgata-Samsung_SSD_850_EVO_2TB_S2RLNX0J502123D
807 for f
in $d vgata-Samsung_SSD_870_QVO_8TB_S5VUNG0N900656V
; do
808 cryptsetup luksOpen
--key-file /p
/dev
/$f/root crypt-
$f-root
809 cryptsetup luksOpen
--key-file /p
/dev
/$f/o crypt-
$f-o
811 mount
-o subvol
=root_trisquelaramo
/dev
/mapper
/crypt-
$d-root /mnt
812 mount
-o subvol
=a
/dev
/mapper
/crypt-
$d-root /mnt
/a
813 mount
-o subvol
=o
/dev
/mapper
/crypt-
$d-o /mnt
/o
814 mount
-o subvol
=boot_trisquelaramo
/dev
/sda2
/mnt
/boot
822 c4
() { c
/var
/log
/exim4
; }
824 caa
() { git commit
--amend --no-edit -a; }
837 find -L "$@" -type f
-not \
( -name .svn
-prune -o -name .git
-prune \
838 -o -name .hg
-prune -o -name .editor-backups
-prune \
839 -o -name .undo-tree-history
-prune \
) -printf '%h\0%d\0%p\n' |
sort -t '\0' -n \
840 |
awk -F '\0' '{print $3}' 2>/dev
/null |
while read -r file; do
842 printf "%s\n" "$file"
849 calc
() { echo "scale=3; $*" |
bc -l; }
850 # no having to type quotes, but also no command history:
854 echo "scale=3; $x" |
bc -l
865 ccat
() { # config cat. see a config without extra lines.
866 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
872 # dev/pts needed for pacman signature check
873 for d
in dev proc sys dev
/pts
; do
875 if ! mountpoint
$d &>/dev
/null
; then
876 m s mount
-o bind /$d $d
882 # dev/pts needed for pacman signature check
883 for d
in dev
/pts dev proc sys
; do
885 if mountpoint
$d &>/dev
/null
; then
893 # join options which are continued to multiples lines onto one line
895 while IFS
= read -r line
; do
896 # remove leading spaces/tabs. assumes extglob
897 if [[ $line == "[ ]*" ]]; then
903 elif [[ $line == *=* ]]; then
904 echo "$pastline" >> "$2"
907 pastline
="$pastline $line"
909 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
910 echo "$pastline" >> "$2"
915 # setup for format of postfix, eg:
918 local pastline unified f1 f2
922 _cdiff-prep
"$1" "$f1"
923 _cdiff-prep
"$2" "$f2"
924 cat "$f1" "$f2" |
grep -Po '^[^=]+=' |
sort |
uniq > "$unified"
925 while IFS
= read -r line
; do
926 # the default bright red / blue doesnt work in emacs shell
927 dwdiff
-cblue,red
-A best
-d " ," <(grep "^$line" "$f1" ||
echo ) <(grep "^$line" "$f2" ||
echo ) | colordiff
935 # shellcheck disable=SC2030
936 inotifywait
-m "$dir" -e create
-e moved_to | \
937 while read -r filedir _
file; do
940 calc $
((SECONDS
- start
)) / 60
947 s chown
-R $USER:$USER "$@"
950 # shellcheck disable=SC2032
952 # makes it so chown -R symlink affects the symlink and its target.
953 if [[ $1 == -R ]]; then
955 command chown
-h "$@"
956 command chown
-R "$@"
967 d
() { builtin bg "$@"; }
970 # f would be more natural, but i already am using it for something
971 z
() { builtin fg "$@"; }
974 x
() { builtin kill %%; }
977 diff --strip-trailing-cr -w "$@" # diff content
985 safe_rename
"$x" "$y"
990 # usage: dfp MOUNTPOINT [SECOND_INTERVAL]
991 # SECOND_INTERVAL defaults to 90
994 local a b mp interval
998 echo "dfp: error, missing 1st arg" >&2
1002 a
=$
(df
--output=used
$mp |
tail -n1)
1004 b
=$
(df
--output=used
$mp |
tail -n1)
1005 printf "used mib: %'d mib/min: %s\n" $
(( b
/1000 )) $
(( (b-a
) / (interval
* 1000 / 60 ) ))
1009 # get ipv4 ip from HOST. or if it is already a number, return that
1017 getent ahostsv4
"$host" |
awk '{ print $1 }' |
head -n1
1023 command dig +nostats
+nocmd
"$@"
1025 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
1029 dig +nordflag
"$@" |
sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' |
while read -r l
; do
1030 if [[ $l == [^\
;]* ]]; then
1034 printf "%s" "$sec" |
sort
1042 # compare digs to the 2 servers
1043 # usage: digdiff @server1 @server2 DIG_ARGS
1044 # note: only the soa master nameserver will respond with
1045 # ra "recursive answer" flag. That difference is meaningless afaik.
1052 digsort
$s1 "$@" |
tee /tmp
/digdiff
1053 diff -u /tmp
/digdiff
<(digsort
$s2 "$@")
1056 # date in a format i like reading
1058 date "+%A, %B %d, %r" "$@"
1063 # date with all digits in a format i like
1067 ccomp
date dt dtr dtd
1069 dus
() { # du, sorted, default arg of
1070 du
-sh ${@:-*} |
sort -h
1075 e
() { printf "%s\n" "$*"; }
1083 printf "%qEOL\n" "${arg}"
1084 printf "%s" "${arg}" |
& hexdump -C
1088 # echo variables. print var including escapes, etc, like xxd for variable
1094 if [[ -v $arg ]]; then
1095 printf "%qEOL\n" "${!arg}"
1096 printf "%s" "${!arg}" |
& hexdump -C
1098 echo arg
$arg is
unset
1104 [[ ${#@} == 2 ]] ||
{ echo "error: ediff requires 2 arguments"; return 1; }
1105 emacs
--eval "(ediff-files \"$1\" \"$2\")"
1109 # shellcheck disable=SC2120 # we expect to pass arguments in use outside this file
1112 tail -F /var
/log
/exim
4/mainlog
/var
/log
/exim
4/*main
/var
/log
/exim
4/paniclog
/var
/log
/exim
4/*panic
-n 200 "$@"
1116 tail -F /var
/log
/exim
4/mainlog
-n 200 "$@"
1119 tail -F /var
/log
/exim
4/mymain
-n 200 "$@"
1121 ccomp
tail etail etail2
1123 # ran into this online, trying it out
1125 ( "$@" &>/dev
/null
& disown )
1129 ssh "$@" cat .ssh
/authorized_keys
{,2}
1133 # print exim old pids
1135 local configtime pid piduptime now daemonpid
1136 printf -v now
'%(%s)T' -1
1137 configtime
=$
(stat
-c%Y
/var
/lib
/exim
4/config.autogenerated
)
1138 if [[ -s /run
/exim
4/exim.pid
]]; then
1139 daemonpid
=$
(cat /run
/exim
4/exim.pid
)
1141 for pid
in $
(pgrep
-f '^/usr/sbin/exim4( |$)'); do
1142 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
1143 if [[ $pid == "$daemonpid" ]]; then
1146 piduptime
=$
(awk -v ticks
="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { printf "%9.0f\n", now - ($20/ticks) }' /proc
/uptime RS
=')' /proc
/$pid/stat
) ||
: # sometimes pids disappear pretty fast
1147 if (( configtime
> now
- piduptime
)); then
1153 # exim tail but only watch lines from new pids
1156 for pid
in $
(eoldpids
); do
1159 if [[ $oldpids ]]; then
1160 etail |
awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
1165 # exim watch as old pids go away
1167 local configtime pid piduptime now tmpstr
1173 mapfile
-t oldpids
<<<"$tmpstr"
1174 if (( ! ${#oldpids[@]} )); then
1177 # print the date every 20 iterations
1178 if (( ! count
% 20 )); then
1182 ps
-f -p "${oldpids[*]}"
1188 less /var
/log
/exim
4/mainlog
1192 exiqgrep
-ir.\
* -o 60 |
while read -r i
; do
1195 hlm exigrep
$i /var
/log
/exim
4/mainlog |
cat ||
:
1199 # other ways to get the list of message ids:
1200 # exim -bp | awk 'NF == 4 {print $3}'
1201 # # this is slower 160ms, vs 60.
1203 exiqgrep
-ir.\
* |
xargs exim
-Mrm
1208 mkdir
-p /tmp
/edev
/etc
1209 cp -ra /etc
/exim4
/tmp
/edev
/etc
1210 cp -ra /etc
/alias* /tmp
/edev
/etc
1211 find /tmp
/edev
/etc
/exim4
-type f
-execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
1215 update-exim4.conf
-d /tmp
/edev
/etc
/exim4
-o /tmp
/edev
/e.conf
1219 # show important information about incoming mail in the exim log
1221 sed -rn '/testignore|jtuttle|eximbackup/!s/^[^ ]+ ([^ ]+) [^ ]+ [^ ]+ <= ([^ ]+).*T="(.*)" from (<[^ ]+> .*$)/\1 \4\n \3/p' <${1:-/var/log/exim4/mainlog}
1224 # 2nd line is message-id:
1226 sed -rn '/testignore|jtuttle|eximbackup/!s/^[^ ]+ ([^ ]+) [^ ]+ [^ ]+ <= ([^ ]+).* id=([^ ]+) T="(.*)" from (<[^ ]+> .*$)/\1 \5\n \3\n \4/p' <${1:-/var/log/exim4/mainlog}
1229 tail -F /var
/log
/exim
4/mainlog |
sed -rn '/testignore|jtuttle|eximbackup/!s/^[^ ]+ ([^ ]+) [^ ]+ [^ ]+ <= ([^ ]+).*T="(.*)" from (<[^ ]+> .*$)/\1 \4\n \3/p'
1236 # find array. make an array of file names found by find into $x
1237 # argument: find arguments
1238 # return: find results in an array $x
1239 while read -rd ''; do
1241 done < <(find "$@" -print0);
1244 faf
() { # find all files. use -L to follow symlinks
1245 find "$@" -not \
( -name .svn
-prune -o -name .git
-prune \
1246 -o -name .hg
-prune -o -name .editor-backups
-prune \
1247 -o -name .undo-tree-history
-prune \
) -type f
2>/dev
/null
1250 # usage ffconcat FILES_TO_CONCAT OUTPUT_FILE
1254 printf "file '%s'\n" "$1" >$tmpf
1255 while (( $# > 1 )); do
1257 printf "file '%s'\n" "$1" >>$tmpf
1259 # https://trac.ffmpeg.org/wiki/Concatenate
1260 ffmpeg
-f concat
-safe 0 -i $tmpf -c copy
"$1"
1265 if (( $# == 0 )); then
1266 echo ffremux error expected args
>&2
1271 tmpf
=$tmpd/"${f##*/}"
1272 ffmpeg
-i "$f" -c:v copy
-c:a copy
$tmpf
1280 # absolute path of file/dir without resolving symlinks.
1282 # Most of the time, I want this where I would normally use readlink.
1283 # This is what realpath -s does in most cases, but sometimes it
1284 # actually resolves symlinks, at least when they are in /.
1286 # Note, if run on a dir, if the final component is relative, it won't
1287 # resolve that. Use the below fpd for that.
1289 # note: we could make a variation of this which
1290 # assigns to a variable name using eval, so that we don't have to do
1291 # x=$(fp somepath), which might save subshell overhead and look nice,
1292 # but I'm not going to bother.
1294 local initial_oldpwd initial_pwd dir base
1295 initial_oldpwd
="$OLDPWD"
1297 if [[ $1 == */* ]]; then
1300 # CDPATH because having it set will cause cd to possibly print output
1302 printf "%s%s\n" "$PWD" "$base"
1303 CDPATH
='' cd "$initial_pwd"
1304 OLDPWD
="$initial_oldpwd"
1306 printf "%s/%s\n" "$PWD" "$1"
1309 # full path of directory without resolving symlinks
1311 local initial_oldpwd initial_pwd dir
1312 initial_oldpwd
="$OLDPWD"
1316 printf "%s%s\n" "$PWD" "$base"
1318 OLDPWD
="$initial_oldpwd"
1325 sudo mailq |gr frozen|
awk '{print $3}' |
while read -r id
; do
1331 echo -e '\n\n##############################\n'
1332 done |
tee -a /tmp
/frozen
1336 while read -r line
; do
1337 printf '%s\n' "$line"
1338 ids
+=("$(printf '%s\n' "$line" |gr frozen|awk '{print $3}')")
1340 echo "sleeping for 2 in case you change your mind"
1342 sudo exim
-Mrm "${ids[@]}"
1346 # like -e for functions. returns on error.
1347 # at the end of the function, disable with:
1349 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
1350 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
1356 local help="Usage: getdir [--help] PATH
1357 Output the directory of PATH, or just PATH if it is a directory."
1358 if [[ $1 == --help ]]; then
1362 if [[ $# -ne 1 ]]; then
1363 echo "getdir error: expected 1 argument, got $#"
1366 if [[ -d $1 ]]; then
1370 dir
="$(dirname "$1")"
1371 if [[ -d $dir ]]; then
1374 echo "getdir error: directory does not exist"
1380 git_empty_branch
() { # start an empty git branch. carefull, it deletes untracked files.
1381 [[ $# == 1 ]] ||
{ echo 'need a branch name!'; return 1;}
1383 root
=$
(gitroot
) ||
return 1 # function to set gitroot
1385 git symbolic-ref HEAD refs
/heads
/$1
1390 # shellcheck disable=SC2120
1392 local help="Usage: gitroot [--help]
1393 Print the full path to the root of the current git repo
1395 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
1396 and works in older versions of git which did not have that."
1397 if [[ $1 == --help ]]; then
1402 p
=$
(git rev-parse
--git-dir) ||
{ echo "error: not in a git repo" ; return 1; }
1403 [[ $p != /* ]] && p
=$PWD
1409 local args gdb
=false
1411 if [[ $EMACSDIR ]]; then
1412 path-add
"$EMACSDIR/lib-src" "$EMACSDIR/src"
1415 if [[ $DISPLAY ]]; then
1419 if (( $# == 0 )); then
1422 # duplicate -c, but oh well
1423 if ! pgrep
-u $EUID emacsclient
; then
1424 if (( $# == 0 )) && type -p gdb
&>/dev
/null
; then
1430 if [[ $EMACSDIR ]]; then
1432 # todo: we don't have to alter HOME since emacs 29+, we can set
1433 # user-emacs-directory with the flag --init-directory
1435 # Alter the path here, otherwise the nfs mount gets triggered on the
1436 # first path lookup when emacs is not being used.
1437 # shellcheck disable=SC2098 disable=SC2097 # false positive
1438 PATH
="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME
=$HOME HOME
=$EMACSDIR m emacsclient
-a "" $args "$@"
1441 # due to a bug, we cant debug from the start unless we get a new gdb
1442 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
1443 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
1444 m emacsclient
-a "" $args "$@"
1446 cd "/a/opt/emacs-$(distro-name)$(distro-num)"
1447 s gdb
-p "$(pgrep -f 'emacs --daemon')" -ex c
1450 m emacsclient
-a "" $args "$@"
1455 # g pipe. like: cmd | emacs. save cmd output to tmp file, then edit.
1461 #like cmd &> tempfile; emacs tempfile
1463 # note: a useful workflow for doing mass replace on my files:
1465 ## remove any false positives, or manually edit them. rename files if needed.
1466 # sedi 's/REGEX/REPLACEMENT/' $(gr '^/' /a/tmp/gtmp)
1471 # g command substitution
1476 # force terminal version
1482 # quit will prompt if the program crashes.
1483 gdb
-ex=r
-ex=quit
--args emacs
"$@"; r
;
1487 # kill the emacs daemon
1492 grep -iIP --color=auto
"$@" ||
return $?
1494 grr
() { # grep recursive
1495 # Don't return 1 on nonmatch because this is meant to be
1496 # interactive, not in a conditional.
1497 if [[ ${#@} == 1 ]]; then
1498 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto
"$@" . ||
[[ $?
== 1 ]]
1500 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto
"$@" ||
[[ $?
== 1 ]]
1508 # recursive everything. search for files/dirs and lines. rs = easy chars to press
1512 find "$@" -not \
( -name .svn
-prune -o -name .git
-prune \
1513 -o -name .hg
-prune -o -name .editor-backups
-prune \
1514 -o -name .undo-tree-history
-prune \
) 2>/dev
/null |
grep -iP --color=auto
"$query"
1518 # horizontal row. used to break up output
1521 # 180 is long enough.
1522 blocks
=██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
1523 printf "%s\n" "$(tput setaf 5 2>/dev/null ||:)${blocks:0:${COLUMNS:-180}}$(tput sgr0 2>/dev/null||:)"
1527 local col input_len
=0
1529 input_len
=$
((input_len
+ 1 + ${#arg}))
1531 col=$
((60 - input_len
))
1532 printf "\e[1;97;41m%s" "$*"
1533 if (( col > 0 )); then
1534 # shellcheck disable=SC2046 # needed to work as intended. a better way would be like hr above.
1535 printf "\e[1;97;41m \e[0m%.0s" $
(eval echo "{1..${col}}")
1539 hlm
() { hl
"$*"; "$@"; }
1541 hrcat
() { local f
; for f
; do [[ -f $f ]] ||
continue; hr
; echo "$f"; cat "$f"; done }
1544 # get latest hub and run it
1545 # main command to use:
1546 # hub pull-request --no-edit
1547 # --no-edit means to use the first commit\'s message as the pull request message.
1548 # If that fails, try doing
1549 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
1550 # where branch is usually master. it does the pr against your current branch.
1552 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1553 # it\'s at ~/.config/hub
1555 local up uptar updir p re
1556 # example https://github.com/github/hub/releases/download/v2.14.2/hub-linux-amd64-2.14.2.tgz
1557 up
=$
(wget
-q -O- https
://api.github.com
/repos
/github
/hub
/releases
/latest | jq
-r .assets
[].browser_download_url |
grep linux-amd64
)
1559 if [[ ! $up ||
$up =~
$re ]]; then
1560 echo "failed to get good update url. got: $up"
1564 if [[ ! -e /a
/opt
/$updir ]]; then
1565 rm -rf /a
/opt
/hub-linux-amd64
*
1567 tar -C /a
/opt
-zxf /a
/opt
/$uptar
1570 if ! which hub
&>/dev
/null
; then
1571 sudo
/a
/opt
/$updir/install
1574 # save token across computers
1575 if [[ ! -L ~
/.config
/hub
]]; then
1576 if [[ -e ~
/.config
/hub
]]; then
1577 mv ~
/.config
/hub
/p
/c
/subdir_files
/.config
/
1579 if [[ -e /p
/c
/subdir_files
/.config
/hub
]]; then
1593 # cvs update -C FILE
1598 # potentially useful command translation
1599 # https://fling.seas.upenn.edu/~giesen/dynamic/wordpress/equivalent-commands-for-git-svn-and-cvs/
1601 # importing cvs repo into git using git-cvs package:
1602 # /f/www $ /usr/lib/git-core/git-cvsimport -C /f/www-git
1618 find -L "$@" -not \
( -name .svn
-prune -o -name .git
-prune \
1619 -o -name .hg
-prune -o -name .editor-backups
-prune \
1620 -o -name .undo-tree-history
-prune \
) -iname "*$glob*" 2>/dev
/null
1624 # insensitive find here. args are combined into the search string.
1625 # -L = follow symlinks
1626 find -L .
-not \
( -name .svn
-prune -o -name .git
-prune \
1627 -o -name .hg
-prune -o -name .editor-backups
-prune \
1628 -o -name .undo-tree-history
-prune \
) -iname "*$**" 2>/dev
/null
1632 # insensitive find directory
1633 find -L .
-type d
-not \
( -name .svn
-prune -o -name .git
-prune \
1634 -o -name .hg
-prune -o -name .editor-backups
-prune \
1635 -o -name .undo-tree-history
-prune \
) -iname "*$**" 2>/dev
/null
1640 sudo iptables
-A INPUT
-s $1 -j DROP
1645 grep -Il "" "$@" &>/dev
/null
1652 # journalctl with times in the format the --since= and --until= options accept
1653 jrt
() { journalctl
-e -n100000 -o short-full
"$@"; }
1654 jr
() { journalctl
-e -n100000 "$@" ; }
1655 jrf
() { journalctl
-n1000 -f "$@" ; }
1657 # the invocation id is "assigned each time the unit changes from an inactive
1658 # state into an activating or active state" man systemd.exec
1659 journalctl
-e --no-tail -u exim4 _SYSTEMD_INVOCATION_ID
="$(systemctl show -p InvocationID --value $1)"
1661 ccomp journalctl jr jrf jru
1666 if [[ $PWD == /[iap
] ]]; then
1667 command ls -A --color=auto
-I lost
+found
"$@"
1669 command ls -A --color=auto
"$@"
1673 lcn
() { locate -i "*$**"; }
1675 lg
() { LC_COLLATE
=C.UTF-8 ll
--group-directories-first "$@"; }
1677 lt
() { ll
-tr "$@"; }
1679 lld
() { ll
-d "$@"; }
1681 ccomp
ls l lg lt lld ll
1687 for dirs in false true
; do
1689 if [[ -d $f ]]; then
1691 # reverse the order to rename the nested dirs first.
1692 # note: 0 element is the dir itself
1693 for ((i
=${#all[@]}-1; i
>=1; i--
)); do
1695 if $dirs && [[ -d $a ]]; then
1696 # e dirs low "$a" # debug
1698 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1700 # e not dirs low "$a" # debug
1705 # just rename all the top level args on the second pass
1707 # e final dirs low "$f" # debug
1714 low
() { # make filenames lowercase, remove bad chars
1717 arg
="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1719 if (( ${#dir} == ${#arg} )); then
1723 new
="${f,,}" # downcase
1724 # shellcheck disable=SC2031 # seems like a shellcheck bug
1725 new
="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1726 new
="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1727 new
="${new%"${new##*[[:alnum:]]}"}"
1728 # remove bad underscores, like __ and _._
1729 new
=$
(echo $new |
sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1730 safe_rename
"$dir/$f" "$dir/$new" ||
return 1
1735 lower
() { # make first letter of filenames lowercase.
1738 if [[ ${x::1} == [A-Z
] ]]; then
1739 y
=$
(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1740 safe_rename
"$x" "$y" ||
return 1
1746 k
() { # history search
1747 grep -iP --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
tail -n 80 ||
[[ $?
== 1 ]];
1749 ks
() { # history search with context
1750 # args are an extended regex used by sed
1751 history |
sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" |
tail -n 80 ||
[[ $?
== 1 ]];
1753 ksu
() { # history search unique
1754 grep -P --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
uniq ||
[[ $?
== 1 ]];
1757 # todo: id like to do maybe a daily or hourly cronjob to
1758 # check that my history file size is increasing. Ive had it
1759 # inexplicably truncated in the past.
1762 HISTTIMEFORMAT
='' history |
awk -v IGNORECASE
=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1763 read -r -p "press anything but contrl-c to delete"
1764 for entry
in $
(HISTTIMEFORMAT
='' history |
awk -v IGNORECASE
=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' |
tac); do
1770 # history without the date
1772 history "$@" | cut
-d' ' -f 7-
1775 ccomp
grep k ks ksu histrm
1779 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1780 make -qp |
awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1792 # mkdir the last arg, cp the rest into it
1795 cp "${@:1:$#-1}" "${@: -1}"
1799 mv "${@:1:$#-1}" "${@: -1}"
1802 mkt
() { # mkdir and touch file
1804 mkdir
-p "$(dirname "$path")"
1808 # shellcheck disable=SC2032
1809 mkdir
() { command mkdir
-p "$@"; }
1812 # https://github.com/HenriWahl/Nagstamon/issues/357
1813 if ! pgrep
-f /usr
/bin
/dunst
>/dev
/null
; then
1816 /usr
/bin
/nagstamon
&
1821 screen
-RD -S profanity
1824 # i dont want to wait for konsole to exit...
1826 command prof
&>/dev
/null
&
1831 printf '\033[1A\033[K'; printf "%s\n" "$l"| ts
"%F %T" |
tee -a /p
/self-chat.log
1836 # cant use s because sudo -i doesnt work for passwordless sudo command
1839 sudo nmtui-connect
"$@"
1849 if shopt nullglob
>/dev
/null
; then
1863 # shellcheck disable=SC2024
1865 for f
in /var
/log
/exim
4/paniclog
/var
/log
/exim
4/*panic
; do
1867 if [[ -s $f ]]; then
1868 echo ================== $f =============
1869 s
tee -a /var
/log
/exim
4/$base-archive <$f
1877 ping() { command ping -O "$@"; }
1878 p8
() { ping "$@" 8.8.8.8; }
1879 p6
() { ping6
"$@" 2001:4860:4860::8888; }
1881 pkx
() { # package extract
1882 local pkg cached tmp f
1885 # shellcheck disable=SC2012
1886 cached
=$
(ls -t /var
/cache
/apt
/archives
/${pkg}_
* |
tail -n1 2>/dev
/null
) ||
:
1887 if [[ $cached ]]; then
1890 m aptitude download
$pkg ||
return 1
1892 tmp
=(*); f
=${tmp[0]} # only 1 expected
1901 tmpf
=$
(pgrep
-f "$*")
1902 mapfile
-t pids
<<<"$tmpf"
1905 # shellcheck disable=SC2128
1911 0) echo "no pid found" ;;
1920 help="Usage: psg [--help] GREP_ARGS
1921 grep ps and output in a nice format"
1922 if [[ $1 == --help ]]; then
1927 # final grep is because some commands tend to have a lot of trailing spaces
1928 y
=$
(echo "$x" |
grep -iP "$@" |
grep -o '.*[^ ]') ||
:
1930 echo "$x" |
head -n 1 ||
[[ $?
== 141 ]]
1935 pubip
() { curl
-4s https
://icanhazip.com
; }
1936 pubip6
() { curl
-6s https
://icanhazip.com
; }
1937 whatismyip
() { pubip
; }
1940 q
() { # start / launch a program in the backround and redir output to null
1944 # shellcheck disable=SC2120
1946 if [[ $HISTFILE ]]; then
1947 history -a # save history
1949 trap ERR
# this avoids a segfault
1951 # i had this redir, not sure why
1952 # exit "$@" 2>/dev/null
1955 # scp is insecure and deprecated.
1957 rsync
-Pt --inplace "$@"
1962 # available high ports are 1024-65535,
1963 # but lets skip things that are more likely to be in use
1966 print(secrets.SystemRandom().randrange(10002,65500))
1972 # shellcheck disable=SC1090 # expected to not follow
1982 # rsync, root is required to keep permissions right.
1983 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1984 # --no-times --delete
1985 # basically, make an exact copy, use checksums instead of file times to be more accurate
1986 rsync
-ahvic --delete "$@"
1989 # like rlu, but dont delete files on the target end which
1990 # do not exist on the original end.
1994 # rl without preserving modification time.
1995 rsync
-ahvic --delete --no-t "$@"
1997 # [RSYNC_OPTS] HOST PATH
1999 # eg. rsu -opts frodo /testpath
2000 # relative paths will expanded with readlink -f.
2001 opts
=("${@:1:$#-2}") # 1 to last -2
2002 path
="${*:$#}" # last
2003 host="${*:$#-1:1}" # last -1
2004 if [[ $path == .
* ]]; then
2005 path
=$
(readlink
-f $path)
2007 m rsync
-ahvi --relative --no-implied-dirs "${opts[@]}" "$path" "root@$host:/";
2009 ccomp rsync rsd rsa rst rsu
2011 # find programs listening on a port
2014 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
2015 s ss
-lpn state listening sport
= $port
2020 if [[ $
(systemctl is-active nscd ||
:) != inactive
]]; then
2025 hr
; s ss
-lpn sport
= 53
2026 if systemctl is-enabled dnsmasq
&>/dev
/null ||
[[ $
(systemctl is-active dnsmasq ||
:) != inactive
]]; then
2027 # this will fail is dnsmasq is failed
2028 hr
; m ser status dnsmasq |
cat ||
:
2030 hr
; echo $f:; ccat
$f
2031 hr
; m grr
'^ *(servers-file|server) *=|^ *no-resolv *$' /etc
/dnsmasq.conf
/etc
/dnsmasq.d
2032 f
=/etc
/dnsmasq-servers.conf
2033 hr
; echo $f:; ccat
$f
2036 echo /etc
/nsswitch.conf
:
2037 grep '^ *hosts:' /etc
/nsswitch.conf
2038 if systemctl is-enabled systemd-resolved
&>/dev
/null ||
[[ $
(systemctl is-active systemd-resolved ||
:) != inactive
]]; then
2039 hr
; m ser status systemd-resolved |
cat ||
:
2040 hr
; m resolvectl status |
cat
2048 if [[ $
(systemctl is-active nscd ||
:) != inactive
]]; then
2052 m sudo nscd
-i hosts
2054 if [[ $
(systemctl is-active dnsmasq ||
:) != inactive
]]; then
2055 m sudo systemctl restart dnsmasq
2057 if [[ $
(systemctl is-active systemd-resolved ||
:) != inactive
]]; then
2058 m sudo systemctl restart systemd-resolved
2060 if type -P resolvectl
&>/dev
/null
; then
2061 resolvectl flush-caches
2065 # add annoyingly long argument which should be the default
2067 sed -i --follow-symlinks "$@"
2073 ssh fencepost
head -n 300 /gd
/gnuorg
/EventAndTravelInfo
/rms-current-trips.txt |
less
2082 command sudo
"$@" ||
return $?
2087 # I use a function because otherwise we cant use in a script,
2088 # cant assign to variable.
2090 # note: gksudo is recommended for X apps because it does not set the
2091 # home directory to the same, and thus apps writing to ~ fuck things up
2092 # with root owned files.
2094 if [[ $EUID != 0 ||
$1 == -* ]]; then
2095 # shellcheck disable=SC2034
2096 SUDOD
="$PWD" command sudo
-i "$@"
2102 sb
() { # sudo bash -c
2103 # use sb instead of s is for sudo redirections,
2104 # eg. sb 'echo "ok fine" > /etc/file'
2105 # shellcheck disable=SC2034
2107 sudo
-i bash
-c "$@"
2110 se
() { s urun
0077 "$@"; }
2113 safe_rename
() { # warn and dont rename if file exists.
2114 # mv -n exists, but it\'s silent
2115 if [[ $# != 2 ]]; then
2116 echo safe_rename error
: $# args
, need
2 >&2
2119 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
2120 if [[ -e $2 ||
-L $2 ]]; then
2121 echo "Cannot rename $1 to $2 as it already exists."
2130 sudo
dd status
=none of
="$1"
2134 if type -p systemctl
&>/dev
/null
; then
2137 if (( $# >= 3 )); then
2138 echo iank
: ser expected
2 or
less arguments
2145 systemctl
-n 40 status
"$@"
2148 seru
() { systemctl
--user "$@"; }
2149 # like restart, but do nothing if its not already started
2152 if [[ $
(s systemctl
--no-pager show
-p ActiveState
$service ) == ActiveState
=active
]]; then
2153 systemctl restart
$service
2157 setini
() { # set a value in a .ini style file
2158 key
="$1" value
="$2" section
="$3" file="$4"
2159 if [[ -s $file ]]; then
2160 sed -ri -f - "$file" <<EOF
2161 # remove existing keys
2162 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*${key}[[:space:]=]/d}
2164 /^\s*\[$section\]/a $key=$value
2165 # from section to eof, do nothing
2166 /^\s*\[$section\]/,\$b
2167 # on the last line, if we haven't found section yet, add section and key
2179 sgo
() { # service go
2181 ser restart
$service ||
return 1
2182 if type -p systemctl
&>/dev
/null
; then
2188 # ignore services that dont exist
2189 if systemctl
cat $service &>/dev
/null
; then
2191 ser disable
$service
2197 systemctl list-unit-files | rg
"$@"
2202 # disable a warning with:
2203 # shellcheck disable=SC2206 # reasoning
2205 # see bash-template/style-guide.md for justifications
2208 quotes
=2048,2068,2086,2206,2254
2209 others
=2029,2032,2033,2054,2164,
2210 shellcheck
-W 999 -x -e $quotes,$others "$@" ||
return $?
2212 # sk with quotes. For checking scripts that we expect to take untrusted
2213 # input in order to verify we quoted vars.
2216 others
=2029,2033,2054,2164
2217 shellcheck
-W 999 -x -e $others "$@" ||
return $?
2222 for f
in $
(i s |
awk '$1 == "modified:" {print $2}'); do
2223 if istext
"$f" && [[ $
(head -n1 "$f" 2>/dev
/null
) == '#!/bin/bash'* ]]; then
2229 # sl: ssh, but firsh rsync our bashrc and related files to a special
2230 # directory on the remote host if needed.
2232 # Some environment variables and files need to be setup for this to work
2233 # (mine are set at the beginning of this file)
2235 # SL_FILES_DIR: Environment variable. Path to folder which should at
2236 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
2237 # remote hosts (top level symlinks are resolved) unless the host already
2238 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
2239 # control and sync files to separately and already has the ~/.bashrc you
2240 # want. The remote bash will also take its .inputrc config from this
2241 # folder (default of not existing is fine). Mine looks like this:
2242 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
2244 # SL_INFO_DIR: Environment variable. This folder stores info about what
2245 # we detected on the remote system and when we last synced. It will be created
2246 # if it does not exist. Sometimes you may want to forget about a
2247 # remote system, you can use sl --rsync, or the function for that slr
2250 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
2251 # depending on the remote host. Run this string on the remote host the
2252 # first time sl is run (or if we run slr). The result is passed to
2253 # SL_TEST_HOOK. For example,
2254 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
2256 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
2257 # $SL_FILES_DIR to vary the files synced.
2259 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
2260 # example to exclude files within a directory. Note, excluded
2261 # files wont be deleted on rsync, you can add --delete-excluded
2262 # to the rsync command if that is desired.
2264 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
2266 # For when ~/.bashrc is already customized on the remote server, you
2267 # might find it problematic that ~/.bashrc is sourced for ALL ssh
2268 # commands, even in scripts. This paragraph is all about that. bash
2269 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
2270 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
2271 # and if you customize it, probably has bugs from time to time. This is
2272 # bad. Here's how I fix it. I have a special condition to "return" in my
2273 # .bashrc for noninteractive ssh shells (copy that code). Then use this
2274 # function or similar that passes LC_USEBASHRC=t when sshing and I want
2275 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
2276 # separate file because even if I return early on, the whole file gets
2277 # parsed which can fail if there is a syntax error.
2279 # Background on LC_USEBASHRC var (no need to read if you just want to
2280 # use this function): env variables sent across ssh are strictly
2281 # limited, but we get LC_* at least in debian based machines, so we
2282 # just make that * be something no normal program would use. Note, on
2283 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
2284 # set, and the inner shell also allows running a nondefault
2285 # .bashrc. This means the outer shell still ran the default .bashrc,
2286 # but that is the best we can do.
2288 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2
type info_sec force_rsync \
2289 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
2290 declare -a args tmpa
2294 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
2295 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
2296 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
2297 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
2300 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
2301 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
2302 # [-F configfile] [-I pkcs11] [-i identity_file]
2303 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
2304 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
2305 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
2308 if [[ $1 == --rsync ]]; then
2312 # shellcheck disable=SC2153 # intentional
2313 sl_test_cmd
=$SL_TEST_CMD
2314 # shellcheck disable=SC2153 # intentional
2315 sl_test_hook
=$SL_TEST_HOOK
2316 # shellcheck disable=SC2153 # intentional
2317 sl_rsync_args
=$SL_RSYNC_ARGS
2344 # note we dont support things like -4oOption
2345 -[46AaCfGgKkMNnqsTtVvXxYy
]*)
2348 -[bcDEeFIiJLlmOopQRSWw
]*)
2349 # -oOption etc is valid
2350 if (( ${#1} >= 3 )); then
2353 args
+=("$1" "$2"); shift 2
2362 if [[ ! $remote ]]; then
2363 echo $0: error hostname required
>&2
2368 if [[ ! $SL_INFO_DIR ]]; then
2369 echo 'error: missing SL_INFO_DIR env var' >&2
2375 tmpa
=($SL_INFO_DIR/???????????
"$remote")
2377 if [[ -e $sshinfo ]]; then
2378 if $force_rsync; then
2385 tmp
=${sshinfo[0]##*/}
2388 extra_info
=$
(cat $sshinfo)
2390 # we test for string to know ssh succeeded
2391 testbool
="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
2392 testcmd
="if $testbool; then printf y; else printf n; fi"
2393 if ! tmp
=$
(LC_USEBASHRC
=y
command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
2394 echo failed sl
test. doing plain
ssh -v
2395 command ssh -v "${args[@]}" "$remote"
2397 if [[ $tmp == y
* ]]; then
2403 extra_info
="${tmp:1}"
2405 if [[ $sl_test_hook ]]; then
2406 RSYNC_RSH
="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
2409 if $haveinfo && [[ $type == b
]]; then
2411 read -r files_sec _
< <(find -L $SL_FILES_DIR -printf "%T@ %p\n" |
sort -nr ||
[[ $?
== 141 ||
${PIPESTATUS[0]} == 32 ]] )
2412 files_sec
=${files_sec%%.*}
2413 if (( files_sec
> info_sec
)); then
2419 sync_dirname
=${SL_FILES_DIR##*/}
2421 if [[ ! $SL_FILES_DIR ]]; then
2422 echo 'error: missing SL_FILES_DIR env var' >&2
2427 RSYNC_RSH
="ssh ${args[*]}" m rsync
-rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
2429 if $dorsync ||
! $haveinfo; then
2430 sshinfo
=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
2431 [[ -e $SL_INFO_DIR ]] || mkdir
-p $SL_INFO_DIR
2432 printf "%s\n" "$extra_info" >$sshinfo
2435 if [[ $type == b
]]; then
2436 if (( ${#@} )); then
2437 # Theres a couple ways to pass arguments, im not sure whats best,
2438 # but relying on bash 4.4+ escape quoting seems most reliable.
2439 command ssh "${args[@]}" "$remote" \
2440 LC_USEBASHRC
=t bash
-c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash
${@@Q}
2441 elif [[ ! -t 0 ]]; then
2442 # This case is when commands are being piped to ssh.
2443 # Normally, no bashrc gets sourced.
2444 # But, since we are doing all this, lets source it because we can.
2445 cat <(echo .
$sync_dirname/.bashrc
) - |
command ssh "${args[@]}" "$remote" LC_USEBASHRC
=t bash
2447 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC
=t INPUTRC
=$sync_dirname/.inputrc bash
--rcfile $sync_dirname/.bashrc
2451 LC_USEBASHRC
=t
command ssh "${args[@]}" "$remote" ${@@Q}
2453 command ssh "${args[@]}" "$remote" LC_USEBASHRC
=t bash
2456 # this function inspired from https://github.com/Russell91/sshrc
2463 sl
-oControlMaster=no
-oControlPath=/ "$@"
2465 # kill off old shared socket then ssh
2467 m
ssh -O exit "$@" ||
[[ $?
== 255 ]]
2470 ccomp
ssh sl slr sss ssk
2473 if [[ $TERM == alacritty ||
$TERM == xterm-kitty
]]; then
2474 TERM
=xterm-256color LC_USEBASHRC
=t
command ssh "$@"
2476 LC_USEBASHRC
=t
command ssh "$@"
2482 # log with script. timing is $1.t and script is $1.s
2483 # -l to save to ~/typescripts/
2484 # -t to add a timestamp to the filenames
2485 local logdir do_stamp arg_base
2486 (( $# >= 1 )) ||
{ echo "arguments wrong"; return 1; }
2489 while getopts "lt" option
2492 l
) arg_base
=$logdir ;;
2495 echo error
: bad option
2500 shift $
((OPTIND
- 1))
2502 [[ -e $logdir ]] || mkdir
-p $logdir
2503 $do_stamp && arg_base
+=$
(date +%F.
%T
%z
)
2504 script -t $arg_base.s
2> $arg_base.t
2506 splay
() { # script replay
2507 #logRoot="$HOME/typescripts/"
2508 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2509 scriptreplay
"$1.t" "$1.s"
2513 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2514 if [[ $# == 0 ]]; then
2515 sudo
-E bash
-c -l "$(history -p '!!')"
2517 echo this
command redos last
history item. no argument is accepted
2522 # with -ll, less secure but faster.
2523 command srm
-ll "$@"
2528 ssh $1 "/tmp/${2##*/}" "$(printf "%q
\n" "${@:2}")"
2540 tclock
() { # terminal clock
2545 # this goes to full width
2546 #len=${1:-$((COLUMNS -7))}
2549 if (( x
== len
)); then
2551 d
="$(date +%l:%_M) "
2554 d
=$
(date +%l
:%M
:%_S
)
2558 for ((i
=0; i
<x
; i
++)); do
2559 if (( i
% 6 )); then
2577 # test existence / exists
2580 [[ -e "$x" ||
-L "$x" ]] || ret
=1
2586 # normally, i would just execute these commands in the function.
2587 # however, DEBUG is not inherited, so we need to run it outside a function.
2588 # And we want to run set -x afterwards to avoid spam, so we cram everything
2589 # in here, and then it will run after this function is done.
2590 # # set as array to satisfy shellcheck, but it is equivalent to setting it as non-array
2591 PROMPT_COMMAND
=('trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "')
2594 PROMPT_COMMAND
=(prompt-command
)
2595 if [[ $TERM == *(screen
*|xterm
*|rxvt
*) ]]; then
2596 trap 'settitle "$BASH_COMMAND"' DEBUG
2600 # prometheus node curl
2603 host=${1:-127.0.0.1}
2604 s curl
--cert-type PEM
--cert /etc
/prometheus
/ssl
/prometheus_cert.pem
--key /etc
/prometheus
/ssl
/prometheus_key.pem
--cacert /etc
/prometheus
/ssl
/prom_node_cert.pem
--resolve prom_node
:9100:$host -v https
://prom_node
:9100/metrics
2607 tx
() { # toggle set -x, and the prompt so it doesnt spam
2608 if [[ $
- == *x
* ]]; then
2617 # show all processes in the network namespace $1.
2618 # blank entries appear to be subprocesses/threads
2622 sudo
find -L /proc
/[1-9]*/task
/*/ns
/net
-samefile /run
/netns
/$netns | cut
-d/ -f5 | \
2624 x
=$
(ps
-w --no-headers -p $l);
2625 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2629 if ! s ip netns list |
grep -Fx nonet
&>/dev
/null
; then
2630 s ip netns add nonet
2632 sudo
-E env
/sbin
/ip netns
exec nonet sudo
-E -u iank
/bin
/bash
2635 m
() { printf "%s\n" "$*"; "$@"; }
2637 # update file. note: duplicated in mail-setup.
2638 # updates $ur u result to true or false
2639 # updates $reload to true if file updated is in /etc/systemd/system
2641 local tmp tmpdir dest
="$1"
2642 local base
="${dest##*/}"
2643 local dir
="${dest%/*}"
2644 if [[ $dir != "$base" ]]; then
2645 # dest has a directory component
2648 # shellcheck disable=SC2034 # see comment at top of function
2650 tmpdir
="$(mktemp -d)"
2651 cat >$tmpdir/"$base"
2652 tmp
=$
(rsync
-ic $tmpdir/"$base" "$dest")
2654 printf "%s\n" "$tmp"
2655 # shellcheck disable=SC2034 # see comment at top of function
2657 if [[ $dest == /etc
/systemd
/system
/* ]]; then
2658 # shellcheck disable=SC2034 # see comment at top of function
2667 if type -p uprecords
&>/dev
/null
; then
2675 for x
in "$@"; do virsh destroy
"$x"; virsh undefine
"$x"; done
2683 sudo virsh dumpxml
$vm |
sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2684 sed -r "s/listen='[^']+/listen='$ip/"> $t
2685 sudo virsh undefine
$vm
2686 sudo virsh define
$t
2691 vm-set-listen
$1 0.0.0.0
2696 vm-set-listen
$1 127.0.0.1
2700 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2701 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2702 sudo iw dev wls1 scan |
sed -rn "
2703 s/^\Wcapability: (.*)/\1/;Ta;h;b
2704 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2705 # padded to min width of 20
2706 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2710 # Run script by copying it to a temporary location first,
2711 # and changing directory, so we don't have any open
2712 # directories or files that could cause problems when
2729 # spark 1 5 22 13 53
2733 # Copyright (c) Zach Holman, https://zachholman.com
2734 # https://github.com/holman/spark
2736 # As of 2022-10-28, I reviewed github forks that had several newer
2737 # commits, none had anything interesting. I did a little refactoring
2738 # mostly to fix emacs indent bug.
2740 # Generates sparklines.
2743 if [ "X$1" = "X-n" ]; then
2757 # find min/max values
2758 local min
=0xffffffff max
=0
2762 # on Linux (or with bash4) we could use `printf %.0f $n` here to
2763 # round the number but that doesn't work on OS X (bash3) nor does
2764 # `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off
2766 (( n
< min
)) && min
=$n
2767 (( n
> max
)) && max
=$n
2768 numbers
=$numbers${numbers:+ }$n
2772 local ticks
=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █
)
2774 # use a high tick if data is constant
2775 (( min
== max
)) && ticks
=(▅ ▆
)
2778 f
=$
(( ( (max-min
) <<8)/( tc - 1) ))
2783 _spark_echo -n ${ticks[$(( (((n-min)<<8)/f) ))]}
2788 pdfwc() { local f; for f; do echo "$f" "$(pdfinfo "$f" | awk '/^Pages:/ {print $2}')"; done }
2791 # nvm install script appended this to my .bashrc. I dont want to run it all the time,
2792 # so put it in a function.
2794 export NVM_DIR="$HOME/.nvm"
2795 # shellcheck disable=SC1091 # may not exist, & third party
2796 [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" # This loads nvm
2797 # shellcheck disable=SC1091 # may not exist, & third party
2798 [ -s "$NVM_DIR/bash_completion" ] && source "$NVM_DIR/bash_completion" # This loads nvm bash_completion
2803 if date -d 'february 29' &>/dev/null; then
2813 if [[ -e /sys/class/power_supply/AC/online && $(</sys/class/power_supply/AC/online) == 0 ]]; then
2820 # make vim work with my light colortheme terminal.
2822 if [[ -e ~/.vimrc ]]; then
2825 command vim -c ':colorscheme peachpuff' "$@"
2829 # ls count. usage: pass a directory, get the number of files.
2830 # https://unix.stackexchange.com/questions/90106/whats-the-most-resource-efficient-way-to-count-how-many-files-are-in-a-director
2832 # shellcheck disable=SC2790 disable=SC2012 # intentional
2836 # run then notify. close notification after the next prompt.
2839 dunstify -u critical -h string:x-dunst-stack-tag:profanity "$*"
2840 _psrun=(dunstctl close-all)
2843 dunstify -u critical -h string:x-dunst-stack-tag:profanity n
2844 _psrun=(dunstctl close-all)
2850 inotifywait -m "$dir" -e create -e moved_to | while read -r _ _ file; do
2863 mapfile -t cmds <<'EOF'
2864 tail -n +1 /proc/mdstat /etc/mdadm/mdadm.conf /etc/fstab /etc/crypttab
2867 ls -la /dev/disk/by-id
2870 for cmd in "${cmds[@]}"; do
2888 if $use_color && type -p tput &>/dev/null; then
2889 # this is nice for a dark background terminal:
2890 # https://github.com/trapd00r/LS_COLORS
2891 # I would like if there was something similar for light.
2893 # the default bold green is too light.
2894 # this explains the codes: https://gist.github.com/thomd/7667642
2895 export LS_COLORS=ex=1
2897 term_bold="$(tput bold)"
2898 term_red="$(tput setaf 1)"
2899 term_green="$(tput setaf 2)"
2900 # shellcheck disable=SC2034 # expected
2901 term_yellow="$(tput setaf 3)"
2902 term_purple="$(tput setaf 5)"
2903 term_nocolor="$(tput sgr0)" # no font attributes
2905 # unused so far. commented for shellcheck
2906 # term_underl="$(tput smul)"
2907 # term_blue="$(tput setaf 4)"
2908 # term_cyan="$(tput setaf 6)"
2910 # Try to keep environment pollution down, EPA loves us.
2911 unset safe_term match_lhs use_color
2916 if [[ $- == *i* ]]; then
2921 if [[ $EUID == 1000 ]]; then
2928 # this needs to come before next ps1 stuff
2929 # this stuff needs bash 4, feb 2009,
2930 # old enough to no longer condition on $BASH_VERSION anymore
2934 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2936 bind -m vi-command B:shell-backward-word
2937 bind -m vi-command W:shell-forward-word
2940 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2941 unset PROMPT_DIRTRIM
2945 # emacs terminal has problems if this runs slowly,
2946 # so I've thrown a bunch of things at the wall to speed it up.
2948 local return=$? # this MUST COME FIRST
2949 local ps_char ps_color
2952 if [[ $HISTFILE ]]; then
2953 history -a # save history
2957 0) ps_color="$term_purple"
2960 *) ps_color="$term_green"
2961 ps_char="$return \\$"
2964 if [[ ! -O . ]]; then # not owner
2965 if [[ -w . ]]; then # writable
2966 ps_color="$term_bold$term_red"
2968 ps_color="$term_bold$term_green"
2972 # faster than sourceing the file im guessing
2973 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2974 eval "$(< /dev/shm/iank-status)"
2976 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2977 ps_char="@ $ps_char"
2980 if [[ $(jobs -p) ]]; then
2985 # allow a function to specify a command to run after we run the next
2986 # command. Use case: a function makes a persistent notification. If
2987 # we happen to be using that terminal, we can just keep working by
2988 # entering our next command, even a noop in order to dismiss the
2989 # notification, instead of having to explicitly dismiss it.
2990 if [[ ${_psrun[*]} ]]; then
2991 if (( _psrun_count >= 1 )); then
2997 _psrun_count=$(( _psrun_count + 1 ))
3003 # We could test if sudo is active with sudo -nv
3004 # but then we get an email and log of lots of failed sudo commands.
3005 # We could turn those off, but seems better not to.
3006 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
3007 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
3009 if [[ ! $HISTFILE ]]; then
3010 ps_char="NOHIST $ps_char"
3012 PS1="${PS1%"${PS1#*[wW]}"} $jobs_char$psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
3014 # copy of what is automatically added by guix.
3015 # adds [env] to PS1 if GUIX_ENVIRONMENT is set and PS1 contains '$';
3016 if [ -n "$GUIX_ENVIRONMENT" ]; then
3017 if [[ $PS1 =~ (.*)"\\$" ]]; then
3018 PS1="${BASH_REMATCH[1]} [env]\\\$ "
3023 # set titlebar. instead, using more advanced
3025 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
3027 PROMPT_COMMAND=(prompt-command)
3029 if [[ $TERM == screen* ]]; then
3030 _title_escape="\033]..2;"
3032 # somme sites recommend this, i dunno what the diff is.
3033 #_title_escape="\033]30;"
3034 _title_escape="\033]0;"
3037 # make the titlebar be the last command and the current directory.
3041 # These are some checks to help ensure we dont set the title at
3042 # times that the debug trap is running other than the case we
3043 # want. Some of them might not be needed.
3044 if (( ${#FUNCNAME[@]} != 1 || ${#BASH_ARGC[@]} != 2 || BASH_SUBSHELL != 0 )); then
3047 if [[ $1 == prompt-command ]]; then
3050 echo -ne "$_title_escape ${PWD/#$HOME/~} "
3055 # note, this wont work:
3056 # x=$(mktemp); cp a $x
3057 # I havnt figured out why, bigger fish to fry.
3060 # condition from the screen man page i think.
3061 # note: duplicated in tx()
3062 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
3063 trap 'settitle "$BASH_COMMAND"' DEBUG
3070 # * stuff that makes sense to be at the end
3076 if [[ -s "$HOME/.rvm/scripts/rvm" ]]; then
3077 # shellcheck disable=SC1091
3078 source "$HOME/.rvm/scripts/rvm"
3081 # I had this idea to start a bash shell which would run an initial
3082 # command passed through this env variable, then continue on
3083 # interactively. But the use case I had in mind went away.
3085 # if [[ $MY_INIT_CMD ]]; then
3086 # "${MY_INIT_CMD[@]}"
3090 # ensure no bad programs appending to this file will have an affect