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.
8 if [[ -s /a
/bin
/errhandle
/err
]]; then
9 source /a
/bin
/errhandle
/err
10 elif [[ -s $bashrc_dir/err
]]; then
11 # shellcheck source=/a/bin/errhandle/err
12 source $bashrc_dir/err
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
21 # if [[ -s /usr/share/bash-completion/completions/git ]]; then
22 # source /usr/share/bash-completion/completions/git
24 # if [[ -s /usr/share/bash-completion/completions/gitk ]]; then
25 # source /usr/share/bash-completion/completions/gitk
28 # for testing error catching:
44 # remove all aliases. aliases provided by the system tend to get in the way,
45 # for example, error happens if I try to define a function the same name as an alias
48 # remove gnome keyring warning messages
49 # there is probably a more proper way, but I didnt find any easily on google
50 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
51 #unset GNOME_KEYRING_CONTROL
53 # use extra globing features.
55 # include .files when globbing, but ignore files name . and ..
56 # setting this also sets dotglob.
57 export GLOBIGNORE
="*/.:*/.."
59 # Useful info. see man bash.
63 # broken with bash_completion package. Saw a bug for this once. dont anymore.
64 # still broken in wheezy
65 # still buggered in latest stable from the web, version 2.1
66 # perhaps its fixed in newer git version, which fails to make for me
67 # this note is from 6-2014.
68 # still broken in flidas.
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
74 # fix spelling errors for cd, only in interactive shell
76 # append history instead of overwritting it
78 # for compatibility, per gentoo/debian bashrc
80 # attempt to save multiline single commands as single history entries.
87 if [[ $LC_INSIDE_EMACS ]]; then
88 # EMACS is used by bash on startup, but we dont need it anymore.
89 # plus I hit a bug in a makefile which inherited it
91 export LC_INSIDE_EMACS
94 # scp completion does not work, but this doesnt fix it. todo, figure this out
95 #complete -r scp &> /dev/null
96 # todo, remote file completion fails, figure out how to turn it off
97 export NODE_DISABLE_COLORS
=1
98 # This gets rid of ugly terminal escape chars in node repl
99 # sometime, Id like to have completion working in emacs shell for node
100 # the offending chars can be found in lib/readline.js,
101 # things that do like:
102 # stream.write('\x1b[' + (x + 1) + 'G');
103 # We can remove them and keep readline, for example by doing this
105 #!/usr/bin/env nodejs
106 # var readline = require('readline');
107 # readline.cursorTo = function(a,b,c) {};
108 # readline.clearScreenDown = function(a) {};
109 # const repl = require('repl');
110 # var replServer = repl.start('');
112 # no prompt, or else readline complete seems to be confused, based
113 # on our column being different? node probably needs to send
114 # different kind of escape sequence that is not ugly. Anyways,
115 # completion doesnt work yet even with the ugly prompt, so whatever
117 export NODE_NO_READLINE
=1
121 export SSH_CONFIG_FILE_OVERRIDE
=/root
/.ssh
/confighome
123 # emacs has a different default search path than the info command. This
124 # adds the info defaults to emacs, but not the reverse, because I dun
125 # care much about the cli. The search path is only on the cli if you run
126 # "info xxx", or in emacs if you run '(info xxx)', so not that
127 # important, but might as well fix it.
129 # info info says this path is what was compiled, and its not documented
130 # anywhere. Through source grepping, i found it in filesys.h of the info
131 # source in trisquel flidas.
133 # Traling : means for emacs to add its own stuff on to the end.
135 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
:.
:
137 # for openwrt system that has no stty, this is easier than
138 # guarding every time i use it.
139 if ! type -p stty
>/dev
/null
; then
145 if [[ $
- == *i
* ]]; then
146 # for readline-complete.el
147 if [[ $LC_INSIDE_EMACS ]]; then
148 # all for readline-complete.el
150 bind 'set horizontal-scroll-mode on'
151 bind 'set print-completions-horizontally on'
152 bind '"\C-i": self-insert'
156 if [[ $TERM != dumb
]] && test -t 1; then
160 if [[ $KONSOLE_PROFILE_NAME ]]; then
164 if [[ $TERM == alacritty
&& ! -e /usr
/share
/terminfo
/a
/alacritty
]]; then
165 # todo: we should try installing the alacritty terminfo if it is not found
166 # https://github.com/alacritty/alacritty/issues/2838
170 # copying from the alacritty example above,
171 if [[ $TERM == xterm-kitty
]]; then
172 if [[ ! -e /usr
/share
/terminfo
/x
/xterm-kitty
]]; then
175 if [[ -e /a
/opt
/kitty
/shell-integration
/bash
/kitty.bash
]]; then
176 KITTY_SHELL_INTEGRATION
=t
177 source /a
/opt
/kitty
/shell-integration
/bash
/kitty.bash
182 # todo: not sure this works in sakura
184 #bind "\C-w": kill-region
185 # sakura == xterm-256color
187 if [[ $TERM != xterm-kitty
&& $TERM == xterm
* ]]; then
188 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
189 bind '"\e[1;5C": shell-forward-word' 2>/dev
/null
190 bind '"\e[1;5D": shell-backward-word' 2>/dev
/null
192 # make ctrl-backspace work. for konsole, i fixed it through
193 # /home/iank/.local/share/konsole/default.keytab
195 bind '"\eOc": shell-forward-word'
196 bind '"\eOd": shell-backward-word'
198 # i cant remember why i did this, probably to free up some keys to bind
199 # to other things in bash.
200 # other than C-c and C-z, the rest defined by stty -a are, at least in
201 # gnome-terminal, overridden by bash, or disabled by the system
202 stty lnext undef stop undef start undef
208 # fixup broken backspace in chroots
209 xterm-kitty|alacritty
)
211 TERM
=xterm-256color
command chroot
"$@"
216 export BC_LINE_LENGTH
=0
219 export PROFILE_TASKS_TASK_OUTPUT_LIMIT
=100
221 # note, if I use a machine I dont want files readable by all users, set
222 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
224 # i for insensitive. the rest from
225 # X means dont remove the current screenworth of output upon exit
226 # R means to show colors n things
227 # a useful flag is -F aka --quit-if-one-screen
229 export SYSTEMD_LESS
=$LESS
231 export NNN_COLORS
=2136
233 export SL_FILES_DIR
=/b
/ds
/sl
/.iank
234 export SL_INFO_DIR
=/p
/sshinfo
239 if [[ -s $bashrc_dir/path-add-function
]]; then
240 source $bashrc_dir/path-add-function
241 if [[ $SSH_CLIENT ]]; then
242 if grep -qF /home
/iank
/.iank
/e
/e
/etc
/exports
&>/dev
/null
; then
243 export EMACSDIR
=/home
/iank
/.iank
/e
/e
249 # if someone exported $SOE (stop on error), catch errors.
251 # Note, on debian this results in the following warning when in ssh,
252 # hich I haven't figured out how to fix. It doesn't happen if we source
253 # after the shell has started
255 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
256 # bash: warning: cannot start debugger; debugging mode disabled
258 if [[ -e /a
/bin
/errhandle
/err
]]; then
259 source /a
/bin
/errhandle
/err
271 if [[ -s $path ]]; then
273 elif [[ -s $bashrc_dir/$file ]]; then
274 source $bashrc_dir/$file
279 mysrc
/a
/bin
/small-misc-bash
/ll-function
280 mysrc
/a
/bin
/distro-functions
/src
/package-manager-abstractions
285 ### begin FSF section ###
287 # Comments before functions are meant to be good useful
288 # documentation. If they fail at that, please improve them or send Ian a
291 ## copy bash completion
292 # Usage: ORIGINAL_COMMAND TARGET_COMMAND...
294 # It copies how the bash completion works from one command to other
300 if ! c
=$
(complete
-p $src 2>/dev
/null
); then
301 _completion_loader
$src &>/dev
/null ||
:
302 c
=$
(complete
-p $src 2>/dev
/null
) ||
return 0
310 ## directory history tracking and navigation.
312 # cd becomes a function, also aliased to c. b to go back, f to go
313 # forward, cl to list recent directories and choose one.
315 # The finer details you may want to skip:
317 # We also define bl to print the list of back and forward directories.
319 # We keep 2 stacks, forward and back. Unlike with a web browser, the
320 # forward stack is not erased when going somewhere new.
322 # Recent directories are stored in ~/.cdirs.
324 declare -a _dir_forward _dir_back
326 # normally, the top of _dir_back is our current dir. if it isn't,
327 # put it on there, except we don't want to do that when we
328 # just launched a shell
329 if [[ $OLDPWD ]]; then
330 if (( ${#_dir_back[@]} == 0 )) ||
[[ ${_dir_back[-1]} != "$PWD" ]]; then
335 if (( ${#_dir_back[@]} == 0 )) ||
[[ ${_dir_back[-1]} != "$PWD" ]]; then
338 echo "$PWD" >> ~
/.cdirs
345 if (( ${#_dir_back[@]} == 0 )); then
346 echo "nothing left to go back to" >&2
349 top_back
="${_dir_back[-1]}"
351 if [[ $top_back == "$PWD" ]] && (( ${#_dir_back[@]} == 1 )); then
352 echo "already on last back entry" >&2
357 if [[ $top_back == "$PWD" ]]; then
358 # add to dirf if not already there
359 if (( ${#_dir_forward[@]} == 0 )) ||
[[ ${_dir_forward[-1]} != "$top_back" ]]; then
360 _dir_forward
+=("$top_back")
362 unset "_dir_back[-1]"
363 command cd "${_dir_back[-1]}"
365 if (( ${#_dir_forward[@]} == 0 )) ||
[[ ${_dir_forward[-1]} != "$PWD" ]]; then
366 _dir_forward
+=("$PWD")
368 command cd "$top_back"
371 # Interesting feature, not sure I want it.
372 # give us a peek at what is next in the list
373 # if (( ${#_dir_back[@]} >= 2 )); then
374 # printf "%s\n" "${_dir_back[-2]}"
378 # c/b/f Implementation notes:
380 # The top of the back is $PWD
381 # as long as the last directory change was due to c,b,or cl.
383 # Example of stack changes:
409 if (( ${#_dir_forward[@]} == 0 )); then
410 echo "no forward dir left" >&2
413 top_forward
="${_dir_forward[-1]}"
414 unset "_dir_forward[-1]"
417 # give us a peek at what is next in the list
418 # if (( ${#_dir_forward[@]} )); then
419 # printf "%s\n" "${_dir_forward[-1]}"
424 local i line input start
425 local -A buttondirs alines
426 local -a buttons
dirs lines
427 buttons
=( {a..z
} {2.
.9} )
428 if [[ ! -s ~
/.cdirs
]]; then
429 echo nothing
in ~
/.cdirs
435 mapfile
-t lines
<~
/.cdirs
436 start
=$
(( ${#lines[@]} - 1 ))
438 # we have ~33 buttons as of this writing, so lets
439 # prune down the history every once in a while.
440 if (( start
> 500 )); then
441 tac ~
/.cdirs |
awk '!seen[$0]++' |
head -n 200 |
tac | sponge ~
/.cdirs ||
[[ $?
== 141 ]]
444 for (( j
=$start; j
>= 0; j--
)); do
446 if [[ ! $line ||
${alines[$line]} ||
! -d "$line" ||
$line == "$PWD" || line
== "$HOME" ]]; then
450 buttondirs
[${buttons[i]}]="$line"
451 printf "%s %s\n" ${buttons[i]} "$line"
452 if (( i
== ${#buttons[@]} - 1 )); then
458 if (( i
== 0 )); then
459 echo "no dirs in ~/.cdirs"
463 if [[ $input != $
'\n' ]]; then
464 c
"${buttondirs[$input]}"
471 start
=$
(( ${#_dir_back[@]} - 1 ))
473 # cleanup possible repeating of pwd
474 if (( start
>= 0 )) && [[ ${_dir_back[$start]} == "$PWD" ]]; then
475 start
=$
(( start
- 1 ))
478 if (( start
>= 0 )); then
479 for (( i
=$start; i
>= 0 ; i--
)); do
480 printf "%s %s\n" $j ${_dir_back[i]}
482 if (( j
>= max
)); then
489 start
=$
(( ${#_dir_forward[@]} - 1 ))
491 # cleanup possible repeating of pwd
492 if (( start
>= 0 )) && [[ ${_dir_forward[$start]} == "$PWD" ]]; then
493 start
=$
(( start
- 1 ))
495 if (( start
< 0 )); then
500 for (( i
=$start; i
>= 0 ; i--
)); do
501 printf "%s %s\n" $j ${_dir_forward[i]}
503 if (( j
>= max
)); then
509 # pee do. run args as a command with output copied to syslog.
511 # Usage: pd [-t TAG] COMMAND...
513 # -t TAG Override the tag in the syslog. The default is COMMAND with
514 # any path part is removed, eg. for /bin/cat the tag is cat.
516 # You can view the log via "journalctl -t TAG"
522 -t) tag
="$2"; shift 2 ;;
524 echo "PWD=$PWD command: $*" | logger
-t $tag
525 "$@" |
& pee
cat "logger -t $tag" || ret
=$?
526 echo "exited with status=$ret" | pee
cat "logger -t $tag"
527 # this avoids any err-catch
528 (( $ret == 0 )) ||
return $ret
532 # jdo = journal do. Run command as transient systemd service, tailing
533 # its output in the journal until it completes.
535 # Usage: jdo COMMAND...
537 # Compared to pd: commands recognize this is a non-interactive shell.
538 # The service is unaffected if our ssh connection dies, no need to run
541 # Note: The last few lines of any existing entries for a unit by that
542 # name will be output first, and there will be a few second delay at the
543 # start of the command, and a second or so at the end.
545 # Note: Functions and aliases obviously won't work, we resolve the
548 # Note: requires running as root.
550 local cmd cmd_name jr_pid ret
554 if [[ $EUID != 0 ]]; then
555 echo "jdo: error: rerun as root"
559 if [[ $cmd != /* ]]; then
560 cmd
=$
(type -P "$cmd")
563 journalctl
-qn2 -f -u "$cmd_name" &
564 # Trial and error of time needed to avoid missing initial lines.
565 # .5 was not reliable. 1 was not reliable. 2 was not reliable
568 systemd-run
--unit "$cmd_name" --wait --collect "$cmd" "$@" || ret
=$?
569 # The sleep lets the journal output its last line
570 # before the prompt comes up.
572 kill $jr_pid &>/dev
/null ||
:
575 # this avoids any err-catch
576 (( $ret == 0 )) ||
return $ret
584 ....
() { c ..
/..
/..
; }
585 .....
() { c ..
/..
/..
/..
; }
586 ......
() { c ..
/..
/..
/..
/..
; }
591 path
=$
(readlink
-e "$f")
592 echo "cat >$path <<'EOF'"
599 # file cut copy and paste, like the text buffers :)
600 # I havnt tested these.
601 _fbufferinit
() { # internal use
602 ! [[ $my_f_tempdir ]] && my_f_tempdir
=$
(mktemp
-d)
603 rm -rf "${my_f_tempdir:?}"/*
607 cp "$@" "$my_f_tempdir"/
611 mv "$@" "$my_f_tempdir"/
613 fpst
() { # file paste
614 [[ $2 ]] && { echo too many arguments
; return 1; }
616 cp "$my_f_tempdir"/* "$target"
620 local host ip port
file key
621 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" ||
: )
622 file=$
(readlink
-f ~
/.ssh
/known_hosts
)
624 echo "khfix: ssh failed"
627 if [[ $port != 22 ]]; then
628 ip_entry
="[$ip]:$port"
629 host_entry
="[$host]:$port"
635 if [[ $host != $ip ]]; then
636 key
=$
(ssh-keygen
-F "$host_entry" -f $file |
sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
638 grep -Fv "$key" "$file" | sponge
"$file"
641 key
=$
(ssh-keygen
-F "$ip_entry" -f $file |
sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
643 grep -Fv "$key" "$file" | sponge
"$file"
645 ll ~
/.ssh
/known_hosts
648 khfix
() { # known hosts fix
649 _khfix_common
"$@" ||
return 1
659 x
=$
(readlink
-nf "${1:-$PWD}")
660 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
661 echo -n "$x" | xclip
-selection clipboard
665 # a1 = awk {print $1}
666 for field
in {1.
.20}; do
667 eval a
$field"() { awk '{print \$$field}'; }"
670 for num
in {1.
.9}; do
671 eval h
$num"() { head -n$num; }"
676 printf '%d.%d.%d.%d\n' $
(echo $1 |
sed 's/../0x& /g')
680 local f out outdir
in
694 m ffmpeg
-threads 0 -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
695 m ffmpeg
-y -threads 0 -i $in -g 192 -vcodec libvpx-vp9
-vf scale
=-1:720 -max_muxing_queue_size 9999 -b:v
750K
-pass 2 -c:a libvorbis
-qscale:a
5 $out
700 utcl
() { # utc 24 hour time to local hour 24 hour time
701 echo "print( ($1 $(date +%z | sed -r 's/..$//;s/^(-?)0*/\1/')) % 24)"|python3
709 # for running in a fai rescue. iank specific.
711 d
=vgata-Samsung_SSD_850_EVO_2TB_S2RLNX0J502123D
712 for f
in $d vgata-Samsung_SSD_870_QVO_8TB_S5VUNG0N900656V
; do
713 cryptsetup luksOpen
--key-file /p
/dev
/$f/root crypt-
$f-root
714 cryptsetup luksOpen
--key-file /p
/dev
/$f/o crypt-
$f-o
716 mount
-o subvol
=root_trisquelaramo
/dev
/mapper
/crypt-
$d-root /mnt
717 mount
-o subvol
=a
/dev
/mapper
/crypt-
$d-root /mnt
/a
718 mount
-o subvol
=o
/dev
/mapper
/crypt-
$d-o /mnt
/o
719 mount
-o subvol
=boot_trisquelaramo
/dev
/sda2
/mnt
/boot
727 c4
() { c
/var
/log
/exim4
; }
729 caa
() { git commit
--amend --no-edit -a; }
740 # shellcheck disable=SC2033
741 find -L "$@" -type f
-not \
( -name .svn
-prune -o -name .git
-prune \
742 -o -name .hg
-prune -o -name .editor-backups
-prune \
743 -o -name .undo-tree-history
-prune \
) \
744 -exec bash
-c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _
{} \
; 2>/dev
/null
749 calc
() { echo "scale=3; $*" |
bc -l; }
750 # no having to type quotes, but also no command history:
754 echo "scale=3; $x" |
bc -l
761 ccat
() { # config cat. see a config without extra lines.
762 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
768 # dev/pts needed for pacman signature check
769 for d
in dev proc sys dev
/pts
; do
771 if ! mountpoint
$d &>/dev
/null
; then
772 m s mount
-o bind /$d $d
778 # dev/pts needed for pacman signature check
779 for d
in dev
/pts dev proc sys
; do
781 if mountpoint
$d &>/dev
/null
; then
789 # join options which are continued to multiples lines onto one line
791 while IFS
= read -r line
; do
792 # remove leading spaces/tabs. assumes extglob
793 if [[ $line == "[ ]*" ]]; then
799 elif [[ $line == *=* ]]; then
800 echo "$pastline" >> "$2"
803 pastline
="$pastline $line"
805 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
806 echo "$pastline" >> "$2"
811 # setup for format of postfix, eg:
814 local pastline unified f1 f2
818 _cdiff-prep
"$1" "$f1"
819 _cdiff-prep
"$2" "$f2"
820 cat "$f1" "$f2" |
grep -Po '^[^=]+=' |
sort |
uniq > "$unified"
821 while IFS
= read -r line
; do
822 # the default bright red / blue doesnt work in emacs shell
823 dwdiff
-cblue,red
-A best
-d " ," <(grep "^$line" "$f1" ||
echo ) <(grep "^$line" "$f2" ||
echo ) | colordiff
831 # shellcheck disable=SC2030
832 inotifywait
-m "$dir" -e create
-e moved_to | \
833 while read -r filedir _
file; do
836 calc $
((SECONDS
- start
)) / 60
843 s chown
-R $USER:$USER "$@"
846 # shellcheck disable=SC2032
848 # makes it so chown -R symlink affects the symlink and its target.
849 if [[ $1 == -R ]]; then
851 command chown
-h "$@"
852 command chown
-R "$@"
863 d
() { builtin bg "$@"; }
866 # f would be more natural, but i already am using it for something
867 z
() { builtin fg "$@"; }
871 diff --strip-trailing-cr -w "$@" # diff content
879 safe_rename
"$x" "$y"
884 # usage: dfp MOUNTPOINT [SECOND_INTERVAL]
885 # SECOND_INTERVAL defaults to 90
888 local a b mp interval
892 echo "dfp: error, missing 1st arg" >&2
896 a
=$
(df
--output=used
$mp |
tail -n1)
898 b
=$
(df
--output=used
$mp |
tail -n1)
899 printf "used mib: %'d mib/min: %s\n" $
(( b
/1000 )) $
(( (b-a
) / (interval
* 1000 / 60 ) ))
903 # get ipv4 ip from HOST. or if it is already a number, return that
911 getent ahostsv4
"$host" |
awk '{ print $1 }' |
head -n1
917 command dig +nostats
+nocmd
"$@"
919 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
923 dig +nordflag
"$@" |
sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' |
while read -r l
; do
924 if [[ $l == [^\
;]* ]]; then
928 printf "%s" "$sec" |
sort
936 # compare digs to the 2 servers
937 # usage: digdiff @server1 @server2 DIG_ARGS
938 # note: only the soa master nameserver will respond with
939 # ra "recursive answer" flag. That difference is meaningless afaik.
946 digsort
$s1 "$@" |
tee /tmp
/digdiff
947 diff -u /tmp
/digdiff
<(digsort
$s2 "$@")
951 date "+%A, %B %d, %r" "$@"
958 dus
() { # du, sorted, default arg of
959 du
-sh ${@:-*} |
sort -h
964 e
() { printf "%s\n" "$*"; }
972 printf "%qEOL\n" "${arg}"
973 printf "%s" "${arg}" |
& hexdump -C
977 # echo variables. print var including escapes, etc, like xxd for variable
983 if [[ -v $arg ]]; then
984 printf "%qEOL\n" "${!arg}"
985 printf "%s" "${!arg}" |
& hexdump -C
987 echo arg
$arg is
unset
993 [[ ${#@} == 2 ]] ||
{ echo "error: ediff requires 2 arguments"; return 1; }
994 emacs
--eval "(ediff-files \"$1\" \"$2\")"
1000 tail -F /var
/log
/exim
4/mainlog
/var
/log
/exim
4/*main
/var
/log
/exim
4/paniclog
/var
/log
/exim
4/*panic
-n 200 "$@"
1004 tail -F /var
/log
/exim
4/mainlog
-n 200 "$@"
1007 tail -F /var
/log
/exim
4/mymain
-n 200 "$@"
1009 ccomp
tail etail etail2
1014 # print exim old pids
1016 local configtime pid piduptime now daemonpid
1017 printf -v now
'%(%s)T' -1
1018 configtime
=$
(stat
-c%Y
/var
/lib
/exim
4/config.autogenerated
)
1019 if [[ -s /run
/exim
4/exim.pid
]]; then
1020 daemonpid
=$
(cat /run
/exim
4/exim.pid
)
1022 for pid
in $
(pgrep
-f '^/usr/sbin/exim4( |$)'); do
1023 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
1024 if [[ $pid == $daemonpid ]]; then
1027 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
1028 if (( configtime
> now
- piduptime
)); then
1034 # exim tail but only watch lines from new pids
1037 for pid
in $
(eoldpids
); do
1040 if [[ $oldpids ]]; then
1041 etail |
awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
1046 # exim watch as old pids go away
1048 local configtime pid piduptime now
1053 oldpids
=($
(eoldpids
))
1054 if (( ! ${#oldpids[@]} )); then
1057 # print the date every 20 iterations
1058 if (( ! count
% 20 )); then
1062 ps
-f -p "${oldpids[*]}"
1068 less /var
/log
/exim
4/mainlog
1072 exiqgrep
-ir.\
* -o 60 |
while read -r i
; do
1075 hlm exigrep
$i /var
/log
/exim
4/mainlog |
cat ||
:
1079 # other ways to get the list of message ids:
1080 # exim -bp | awk 'NF == 4 {print $3}'
1081 # # this is slower 160ms, vs 60.
1083 exiqgrep
-ir.\
* |
xargs exim
-Mrm
1088 mkdir
-p /tmp
/edev
/etc
1089 cp -ra /etc
/exim4
/tmp
/edev
/etc
1090 cp -ra /etc
/alias* /tmp
/edev
/etc
1091 find /tmp
/edev
/etc
/exim4
-type f
-execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
1095 update-exim4.conf
-d /tmp
/edev
/etc
/exim4
-o /tmp
/edev
/e.conf
1102 # find array. make an array of file names found by find into $x
1103 # argument: find arguments
1104 # return: find results in an array $x
1105 while read -rd ''; do
1107 done < <(find "$@" -print0);
1110 faf
() { # find all files. use -L to follow symlinks
1111 find "$@" -not \
( -name .svn
-prune -o -name .git
-prune \
1112 -o -name .hg
-prune -o -name .editor-backups
-prune \
1113 -o -name .undo-tree-history
-prune \
) -type f
2>/dev
/null
1116 # full path without resolving symlinks
1121 printf "%s/%s\n" $
(cd $dir; pwd) "$base"
1128 sudo mailq |gr frozen|
awk '{print $3}' |
while read -r id
; do
1134 echo -e '\n\n##############################\n'
1135 done |
tee -a /tmp
/frozen
1139 while read -r line
; do
1140 printf '%s\n' "$line"
1141 ids
+=($
(printf '%s\n' "$line" |gr frozen|
awk '{print $3}'))
1143 echo "sleeping for 2 in case you change your mind"
1145 sudo exim
-Mrm "${ids[@]}"
1149 # like -e for functions. returns on error.
1150 # at the end of the function, disable with:
1152 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
1153 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
1159 local help="Usage: getdir [--help] PATH
1160 Output the directory of PATH, or just PATH if it is a directory."
1161 if [[ $1 == --help ]]; then
1165 if [[ $# -ne 1 ]]; then
1166 echo "getdir error: expected 1 argument, got $#"
1169 if [[ -d $1 ]]; then
1173 dir
="$(dirname "$1")"
1174 if [[ -d $dir ]]; then
1177 echo "getdir error: directory does not exist"
1183 git_empty_branch
() { # start an empty git branch. carefull, it deletes untracked files.
1184 [[ $# == 1 ]] ||
{ echo 'need a branch name!'; return 1;}
1186 root
=$
(gitroot
) ||
return 1 # function to set gitroot
1188 git symbolic-ref HEAD refs
/heads
/$1
1193 # shellcheck disable=SC2120
1195 local help="Usage: gitroot [--help]
1196 Print the full path to the root of the current git repo
1198 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
1199 and works in older versions of git which did not have that."
1200 if [[ $1 == --help ]]; then
1205 p
=$
(git rev-parse
--git-dir) ||
{ echo "error: not in a git repo" ; return 1; }
1206 [[ $p != /* ]] && p
=$PWD
1212 # todo: patch emacs so it will look elsewhere. this is kinda sad:
1213 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
1215 local args gdb
=false
1217 if [[ $EMACSDIR ]]; then
1218 path-add
"$EMACSDIR/lib-src" "$EMACSDIR/src"
1221 if [[ $DISPLAY ]]; then
1225 if (( $# == 0 )); then
1228 # duplicate -c, but oh well
1229 if ! pgrep
-u $EUID emacsclient
; then
1230 if (( $# == 0 )) && type -p gdb
&>/dev
/null
; then
1236 if [[ $EMACSDIR ]]; then
1237 # Alter the path here, otherwise the nfs mount gets triggered on the
1238 # first path lookup when emacs is not being used.
1239 PATH
="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME
=$HOME HOME
=$EMACSDIR m emacsclient
-a "" $args "$@"
1242 # due to a bug, we cant debug from the start unless we get a new gdb
1243 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
1244 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
1245 m emacsclient
-a "" $args "$@"
1247 cd /a
/opt
/emacs-$
(distro-name
)$
(distro-num
)
1248 s gdb
-p $
(pgrep
-f 'emacs --daemon') -ex c
1251 m emacsclient
-a "" $args "$@"
1256 # force terminal version
1262 # quit will prompt if the program crashes.
1263 gdb
-ex=r
-ex=quit
--args emacs
"$@"; r
;
1267 # kill the emacs daemon
1272 grep -iIP --color=auto
"$@" ||
return $?
1274 grr
() { # grep recursive
1275 # Don't return 1 on nonmatch because this is meant to be
1276 # interactive, not in a conditional.
1277 if [[ ${#@} == 1 ]]; then
1278 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto
"$@" . ||
[[ $?
== 1 ]]
1280 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto
"$@" ||
[[ $?
== 1 ]]
1288 hr
() { # horizontal row. used to break up output
1289 printf "$(tput setaf 5 2>/dev/null ||:)█$(tput sgr0 2>/dev/null||:)%.0s" $
(eval echo "{1..${COLUMNS:-60}}")
1294 local col input_len
=0
1296 input_len
=$
((input_len
+ 1 + ${#arg}))
1298 col=$
((60 - input_len
))
1299 printf "\e[1;97;41m%s" "$*"
1300 if (( col > 0 )); then
1301 printf "\e[1;97;41m \e[0m%.0s" $
(eval echo "{1..${col}}")
1305 hlm
() { hl
"$*"; "$@"; }
1307 hrcat
() { local f
; for f
; do [[ -f $f ]] ||
continue; hr
; echo "$f"; cat "$f"; done }
1310 # get latest hub and run it
1311 # main command to use:
1312 # hub pull-request --no-edit
1313 # --no-edit means to use the first commit\'s message as the pull request message.
1314 # If that fails, try doing
1315 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
1316 # where branch is usually master. it does the pr against your current branch.
1318 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1319 # it\'s at ~/.config/hub
1321 local up uptar updir p v
1322 # example https://github.com/github/hub/releases/download/v2.14.2/hub-linux-amd64-2.14.2.tgz
1323 up
=$
(wget
-q -O- https
://api.github.com
/repos
/github
/hub
/releases
/latest | jq
-r .assets
[].browser_download_url |
grep linux-amd64
)
1325 if [[ ! $up ||
$up == $re ]]; then
1326 echo "failed to get good update url. got: $up"
1330 if [[ ! -e /a
/opt
/$updir ]]; then
1331 rm -rf /a
/opt
/hub-linux-amd64
*
1333 tar -C /a
/opt
-zxf /a
/opt
/$uptar
1336 if ! which hub
&>/dev
/null
; then
1337 sudo
/a
/opt
/$updir/install
1340 # save token across computers
1341 if [[ ! -L ~
/.config
/hub
]]; then
1342 if [[ -e ~
/.config
/hub
]]; then
1343 mv ~
/.config
/hub
/p
/c
/subdir_files
/.config
/
1345 if [[ -e /p
/c
/subdir_files
/.config
/hub
]]; then
1359 # cvs update -C FILE
1364 # potentially useful command translation
1365 # https://fling.seas.upenn.edu/~giesen/dynamic/wordpress/equivalent-commands-for-git-svn-and-cvs/
1367 # importing cvs repo into git using git-cvs package:
1368 # /f/www $ /usr/lib/git-core/git-cvsimport -C /f/www-git
1383 # -L = follow symlinks
1384 find -L .
-not \
( -name .svn
-prune -o -name .git
-prune \
1385 -o -name .hg
-prune -o -name .editor-backups
-prune \
1386 -o -name .undo-tree-history
-prune \
) -iname "*$**" 2>/dev
/null
1390 # insensitive find directory
1391 find -L .
-type d
-not \
( -name .svn
-prune -o -name .git
-prune \
1392 -o -name .hg
-prune -o -name .editor-backups
-prune \
1393 -o -name .undo-tree-history
-prune \
) -iname "*$**" 2>/dev
/null
1398 sudo iptables
-A INPUT
-s $1 -j DROP
1403 grep -Il "" "$@" &>/dev
/null
1411 journalctl
-n 10000 -f "$@"
1413 jr
() { journalctl
"$@" ; }
1414 jrf
() { journalctl
-f "$@" ; }
1416 journalctl
-u exim4 _SYSTEMD_INVOCATION_ID
=$
(systemctl show
-p InvocationID
--value $1)
1422 if [[ $PWD == /[iap
] ]]; then
1423 command ls -A --color=auto
-I lost
+found
"$@"
1425 command ls -A --color=auto
"$@"
1429 lcn
() { locate -i "*$**"; }
1431 lg
() { LC_COLLATE
=C.UTF-8 ll
--group-directories-first "$@"; }
1433 lt
() { ll
-tr "$@"; }
1435 lld
() { ll
-d "$@"; }
1437 ccomp
ls l lg lt lld ll
1443 for dirs in false true
; do
1445 if [[ -d $f ]]; then
1447 # reverse the order to rename the nested dirs first.
1448 # note: 0 element is the dir itself
1449 for ((i
=${#all[@]}-1; i
>=1; i--
)); do
1451 if $dirs && [[ -d $a ]]; then
1452 # e dirs low "$a" # debug
1454 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1456 # e not dirs low "$a" # debug
1461 # just rename all the top level args on the second pass
1463 # e final dirs low "$f" # debug
1470 low
() { # make filenames lowercase, remove bad chars
1473 arg
="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1475 if (( ${#dir} == ${#arg} )); then
1479 new
="${f,,}" # downcase
1480 new
="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1481 new
="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1482 new
="${new%"${new##*[[:alnum:]]}"}"
1483 # remove bad underscores, like __ and _._
1484 new
=$
(echo $new |
sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1485 safe_rename
"$dir/$f" "$dir/$new" ||
return 1
1490 lower
() { # make first letter of filenames lowercase.
1493 if [[ ${x::1} == [A-Z
] ]]; then
1494 y
=$
(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1495 safe_rename
"$x" "$y" ||
return 1
1501 k
() { # history search
1502 grep -iP --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
tail -n 80 ||
[[ $?
== 1 ]];
1504 ks
() { # history search with context
1505 # args are an extended regex used by sed
1506 history |
sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" |
tail -n 80 ||
[[ $?
== 1 ]];
1508 ksu
() { # history search unique
1509 grep -P --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
uniq ||
[[ $?
== 1 ]];
1512 # todo: id like to do maybe a daily or hourly cronjob to
1513 # check that my history file size is increasing. Ive had it
1514 # inexplicably truncated in the past.
1517 HISTTIMEFORMAT
= history |
awk -v IGNORECASE
=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1518 read -p "press anything but contrl-c to delete"
1519 for entry
in $
(HISTTIMEFORMAT
= history |
awk -v IGNORECASE
=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' |
tac); do
1525 ccomp
grep k ks ksu histrm
1529 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1530 make -qp |
awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1543 mkt
() { # mkdir and touch file
1545 mkdir
-p "$(dirname "$path")"
1549 # shellcheck disable=SC2032
1550 mkdir
() { command mkdir
-p "$@"; }
1553 # https://github.com/HenriWahl/Nagstamon/issues/357
1554 if ! pgrep
-f /usr
/lib
/notification-daemon
/notification-daemon
>/dev
/null
; then
1555 /usr
/lib
/notification-daemon
/notification-daemon
&
1557 /usr
/bin
/nagstamon
&
1561 # cant use s because sudo -i doesnt work for passwordless sudo command
1564 sudo nmtui-connect
"$@"
1574 if shopt nullglob
>/dev
/null
; then
1588 # shellcheck disable=SC2024
1590 for f
in /var
/log
/exim
4/paniclog
/var
/log
/exim
4/*panic
; do
1592 if [[ -s $f ]]; then
1593 echo ================== $f =============
1594 s
tee -a /var
/log
/exim
4/$base-archive <$f
1602 ping() { command ping -O "$@"; }
1603 p8
() { ping "$@" 8.8.8.8; }
1604 p6
() { ping6
"$@" 2001:4860:4860::8888; }
1606 pkx
() { # package extract
1607 local pkg cached tmp f
1610 # shellcheck disable=SC2012
1611 cached
=$
(ls -t /var
/cache
/apt
/archives
/$pkg* |
tail -n1 2>/dev
/null
) ||
:
1612 if [[ $cached ]]; then
1615 aptitude download
$pkg ||
return 1
1617 tmp
=(*); f
=${tmp[0]} # only 1 expected
1625 pid
=($
(pgrep
-f "$*"))
1628 # shellcheck disable=SC2128
1634 0) echo "no pid found" ;;
1643 help="Usage: psg [--help] GREP_ARGS
1644 grep ps and output in a nice format"
1645 if [[ $1 == --help ]]; then
1650 # final grep is because some commands tend to have a lot of trailing spaces
1651 y
=$
(echo "$x" |
grep -iP "$@" |
grep -o '.*[^ ]') ||
:
1653 echo "$x" |
head -n 1 ||
[[ $?
== 141 ]]
1658 pubip
() { curl
-4s https
://icanhazip.com
; }
1659 pubip6
() { curl
-6s https
://icanhazip.com
; }
1660 whatismyip
() { pubip
; }
1663 q
() { # start / launch a program in the backround and redir output to null
1667 # shellcheck disable=SC2120
1669 if [[ $HISTFILE ]]; then
1670 history -a # save history
1672 trap ERR
# this avoids a segfault
1674 # i had this redir, not sure why
1675 # exit "$@" 2>/dev/null
1678 # scp is insecure and deprecated.
1680 rsync
--inplace "$@"
1685 # available high ports are 1024-65535,
1686 # but lets skip things that are more likely to be in use
1689 print(secrets.SystemRandom().randrange(10002,65500))
1704 # rsync, root is required to keep permissions right.
1705 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1706 # --no-times --delete
1707 # basically, make an exact copy, use checksums instead of file times to be more accurate
1708 rsync
-ahvic --delete "$@"
1711 # like rlu, but dont delete files on the target end which
1712 # do not exist on the original end.
1716 # rl without preserving modification time.
1717 rsync
-ahvic --delete --no-t "$@"
1719 # [RSYNC_OPTS] HOST PATH
1721 # eg. rsu -opts frodo /testpath
1722 # relative paths will expanded with readlink -f.
1723 opts
=("${@:1:$#-2}") # 1 to last -2
1724 path
="${*:$#}" # last
1725 host="${*:$#-1:1}" # last -1
1726 if [[ $path == .
* ]]; then
1727 path
=$
(readlink
-f $path)
1729 m rsync
-ahvi --relative --no-implied-dirs "${opts[@]}" "$path" "root@$host:/";
1731 ccomp rsync rsd rsa rst rsu
1733 # find programs listening on a port
1736 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
1737 s ss
-lpn state listening sport
= $port
1742 if [[ $
(systemctl is-active nscd ||
:) != inactive
]]; then
1747 hr
; s ss
-lpn sport
= 53
1748 if systemctl is-enabled dnsmasq
&>/dev
/null ||
[[ $
(systemctl is-active dnsmasq ||
:) != inactive
]]; then
1749 # this will fail is dnsmasq is failed
1750 hr
; m ser status dnsmasq |
cat ||
:
1752 hr
; echo $f:; ccat
$f
1753 hr
; m grr
'^ *(servers-file|server) *=|^ *no-resolv *$' /etc
/dnsmasq.conf
/etc
/dnsmasq.d
1754 f
=/etc
/dnsmasq-servers.conf
1755 hr
; echo $f:; ccat
$f
1758 echo /etc
/nsswitch.conf
:
1759 grep '^ *hosts:' /etc
/nsswitch.conf
1760 if systemctl is-enabled systemd-resolved
&>/dev
/null ||
[[ $
(systemctl is-active systemd-resolved ||
:) != inactive
]]; then
1761 hr
; m ser status systemd-resolved |
cat ||
:
1762 hr
; m resolvectl status |
cat
1770 if [[ $
(systemctl is-active nscd ||
:) != inactive
]]; then
1774 m sudo nscd
-i hosts
1776 if [[ $
(systemctl is-active dnsmasq ||
:) != inactive
]]; then
1777 m sudo systemctl restart dnsmasq
1779 if [[ $
(systemctl is-active systemd-resolved ||
:) != inactive
]]; then
1780 m sudo systemctl restart systemd-resolved
1782 if type -P resolvectl
&>/dev
/null
; then
1783 resolvectl flush-caches
1788 ssh fencepost
head -n 300 /gd
/gnuorg
/EventAndTravelInfo
/rms-current-trips.txt |
less
1797 command sudo
"$@" ||
return $?
1802 # I use a function because otherwise we cant use in a script,
1803 # cant assign to variable.
1805 # note: gksudo is recommended for X apps because it does not set the
1806 # home directory to the same, and thus apps writing to ~ fuck things up
1807 # with root owned files.
1809 if [[ $EUID != 0 ||
$1 == -* ]]; then
1810 # shellcheck disable=SC2034
1811 SUDOD
="$PWD" command sudo
-i "$@"
1817 sb
() { # sudo bash -c
1818 # use sb instead of s is for sudo redirections,
1819 # eg. sb 'echo "ok fine" > /etc/file'
1820 # shellcheck disable=SC2034
1822 sudo
-i bash
-c "$@"
1825 se
() { s urun
0077 "$@"; }
1828 safe_rename
() { # warn and dont rename if file exists.
1829 # mv -n exists, but it\'s silent
1830 if [[ $# != 2 ]]; then
1831 echo safe_rename error
: $# args
, need
2 >2
1834 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1835 if [[ -e $2 ||
-L $2 ]]; then
1836 echo "Cannot rename $1 to $2 as it already exists."
1845 sudo
dd status
=none of
="$1"
1849 if type -p systemctl
&>/dev
/null
; then
1852 if (( $# >= 3 )); then
1853 echo iank
: ser expected
2 or
less arguments
1860 systemctl
-n 40 status
"$@"
1863 seru
() { systemctl
--user "$@"; }
1864 # like restart, but do nothing if its not already started
1867 if [[ $
(s systemctl
--no-pager show
-p ActiveState
$service ) == ActiveState
=active
]]; then
1868 systemctl restart
$service
1872 setini
() { # set a value in a .ini style file
1873 key
="$1" value
="$2" section
="$3" file="$4"
1874 if [[ -s $file ]]; then
1875 sed -ri -f - "$file" <<EOF
1876 # remove existing keys
1877 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1879 /^\s*\[$section\]/a $key=$value
1880 # from section to eof, do nothing
1881 /^\s*\[$section\]/,\$b
1882 # on the last line, if we haven't found section yet, add section and key
1894 sgo
() { # service go
1896 ser restart
$service ||
return 1
1897 if type -p systemctl
&>/dev
/null
; then
1903 # ignore services that dont exist
1904 if systemctl
cat $service &>/dev
/null
; then
1906 ser disable
$service
1912 systemctl list-unit-files | rg
"$@"
1919 # disable a warning with:
1920 # shellcheck disable=SC2206 # reasoning
1922 # see bash-template/style-guide.md for justifications
1925 quotes
=2048,2068,2086,2206
1926 others
=2029,2033,2054,2164
1927 shellcheck
-W 999 -x -e $quotes,$others "$@" ||
return $?
1931 # sl: ssh, but firsh rsync our bashrc and related files to a special
1932 # directory on the remote host if needed.
1934 # Some environment variables and files need to be setup for this to work
1935 # (mine are set at the beginning of this file)
1937 # SL_FILES_DIR: Environment variable. Path to folder which should at
1938 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1939 # remote hosts (top level symlinks are resolved) unless the host already
1940 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1941 # control and sync files to separately and already has the ~/.bashrc you
1942 # want. The remote bash will also take its .inputrc config from this
1943 # folder (default of not existing is fine). Mine looks like this:
1944 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1946 # SL_INFO_DIR: Environment variable. This folder stores info about what
1947 # we detected on the remote system and when we last synced. It will be created
1948 # if it does not exist. Sometimes you may want to forget about a
1949 # remote system, you can use sl --rsync, or the function for that slr
1952 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1953 # depending on the remote host. Run this string on the remote host the
1954 # first time sl is run (or if we run slr). The result is passed to
1955 # SL_TEST_HOOK. For example,
1956 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1958 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1959 # $SL_FILES_DIR to vary the files synced.
1961 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1962 # example to exclude files within a directory. Note, excluded
1963 # files wont be deleted on rsync, you can add --delete-excluded
1964 # to the rsync command if that is desired.
1966 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1968 # For when ~/.bashrc is already customized on the remote server, you
1969 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1970 # commands, even in scripts. This paragraph is all about that. bash
1971 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1972 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1973 # and if you customize it, probably has bugs from time to time. This is
1974 # bad. Here's how I fix it. I have a special condition to "return" in my
1975 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1976 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1977 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1978 # separate file because even if I return early on, the whole file gets
1979 # parsed which can fail if there is a syntax error.
1981 # Background on LC_USEBASHRC var (no need to read if you just want to
1982 # use this function): env variables sent across ssh are strictly
1983 # limited, but we get LC_* at least in debian based machines, so we
1984 # just make that * be something no normal program would use. Note, on
1985 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1986 # set, and the inner shell also allows running a nondefault
1987 # .bashrc. This means the outer shell still ran the default .bashrc,
1988 # but that is the best we can do.
1990 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2
type info_sec force_rsync \
1991 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1992 declare -a args tmpa
1996 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1997 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1998 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1999 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
2002 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
2003 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
2004 # [-F configfile] [-I pkcs11] [-i identity_file]
2005 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
2006 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
2007 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
2010 if [[ $1 == --rsync ]]; then
2015 sl_test_cmd
=$SL_TEST_CMD
2016 sl_test_hook
=$SL_TEST_HOOK
2017 sl_rsync_args
=$SL_RSYNC_ARGS
2044 # note we dont support things like -4oOption
2045 -[46AaCfGgKkMNnqsTtVvXxYy
]*)
2048 -[bcDEeFIiJLlmOopQRSWw
]*)
2049 # -oOption etc is valid
2050 if (( ${#1} >= 3 )); then
2053 args
+=("$1" "$2"); shift 2
2062 if [[ ! $remote ]]; then
2063 echo $0: error hostname required
>&2
2068 if [[ ! $SL_INFO_DIR ]]; then
2069 echo error
: missing
'$SL_INFO_DIR' env var
>&2
2075 tmpa
=($SL_INFO_DIR/???????????
"$remote")
2077 if [[ -e $sshinfo ]]; then
2078 if $force_rsync; then
2085 tmp
=${sshinfo[0]##*/}
2088 extra_info
=$
(cat $sshinfo)
2090 # we test for string to know ssh succeeded
2091 testbool
="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
2092 testcmd
="if $testbool; then printf y; else printf n; fi"
2093 if ! tmp
=$
(LC_USEBASHRC
=y
command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
2094 echo failed sl
test. doing plain
ssh -v
2095 command ssh -v "${args[@]}" "$remote"
2097 if [[ $tmp == y
* ]]; then
2103 extra_info
="${tmp:1}"
2105 if [[ $sl_test_hook ]]; then
2106 RSYNC_RSH
="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
2109 if $haveinfo && [[ $type == b
]]; then
2111 read files_sec _
< <(find -L $SL_FILES_DIR -printf "%T@ %p\n" |
sort -nr ||
[[ $?
== 141 ||
${PIPESTATUS[0]} == 32 ]] )
2112 files_sec
=${files_sec%%.*}
2113 if (( files_sec
> info_sec
)); then
2119 sync_dirname
=${SL_FILES_DIR##*/}
2121 if [[ ! $SL_FILES_DIR ]]; then
2122 echo error
: missing
'$SL_FILES_DIR' env var
>&2
2127 RSYNC_RSH
="ssh ${args[*]}" m rsync
-rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
2129 if $dorsync ||
! $haveinfo; then
2130 sshinfo
=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
2131 [[ -e $SL_INFO_DIR ]] || mkdir
-p $SL_INFO_DIR
2132 printf "%s\n" "$extra_info" >$sshinfo
2135 if [[ $type == b
]]; then
2136 if (( ${#@} )); then
2137 # Theres a couple ways to pass arguments, im not sure whats best,
2138 # but relying on bash 4.4+ escape quoting seems most reliable.
2139 command ssh "${args[@]}" "$remote" \
2140 LC_USEBASHRC
=t bash
-c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash
${@@Q}
2141 elif [[ ! -t 0 ]]; then
2142 # This case is when commands are being piped to ssh.
2143 # Normally, no bashrc gets sourced.
2144 # But, since we are doing all this, lets source it because we can.
2145 cat <(echo .
$sync_dirname/.bashrc
) - |
command ssh "${args[@]}" "$remote" LC_USEBASHRC
=t bash
2147 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC
=t INPUTRC
=$sync_dirname/.inputrc bash
--rcfile $sync_dirname/.bashrc
2151 LC_USEBASHRC
=t
command ssh "${args[@]}" "$remote" ${@@Q}
2153 command ssh "${args[@]}" "$remote" LC_USEBASHRC
=t bash
2156 # this function inspired from https://github.com/Russell91/sshrc
2163 sl
-oControlMaster=no
-oControlPath=/ "$@"
2165 # kill off old shared socket then ssh
2167 m
ssh -O exit "$@" ||
[[ $?
== 255 ]]
2170 ccomp
ssh sl slr sss ssk
2173 if [[ $TERM == alacritty ||
$TERM == xterm-kitty
]]; then
2174 TERM
=xterm-256color LC_USEBASHRC
=t
command ssh "$@"
2176 LC_USEBASHRC
=t
command ssh "$@"
2182 # log with script. timing is $1.t and script is $1.s
2183 # -l to save to ~/typescripts/
2184 # -t to add a timestamp to the filenames
2185 local logdir do_stamp arg_base
2186 (( $# >= 1 )) ||
{ echo "arguments wrong"; return 1; }
2189 while getopts "lt" option
2192 l
) arg_base
=$logdir ;;
2193 t
) do_stamp
=true
;;
2196 shift $
((OPTIND
- 1))
2198 [[ -e $logdir ]] || mkdir
-p $logdir
2199 $do_stamp && arg_base
+=$
(date +%F.
%T
%z
)
2200 script -t $arg_base.s
2> $arg_base.t
2202 splay
() { # script replay
2203 #logRoot="$HOME/typescripts/"
2204 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2205 scriptreplay
"$1.t" "$1.s"
2209 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2210 if [[ $# == 0 ]]; then
2211 sudo
-E bash
-c -l "$(history -p '!!')"
2213 echo this
command redos last
history item. no argument is accepted
2218 # with -ll, less secure but faster.
2219 command srm
-ll "$@"
2224 ssh $1 /tmp
/${2##*/} $
(printf "%q\n" "${@:2}")
2236 tclock
() { # terminal clock
2241 # this goes to full width
2242 #len=${1:-$((COLUMNS -7))}
2245 if (( x
== len
)); then
2247 d
="$(date +%l:%_M) "
2250 d
=$
(date +%l
:%M
:%_S
)
2254 for ((i
=0; i
<x
; i
++)); do
2255 if (( i
% 6 )); then
2273 # test existence / exists
2276 [[ -e "$x" ||
-L "$x" ]] || ret
=1
2282 # normally, i would just execute these commands in the function.
2283 # however, DEBUG is not inherited, so we need to run it outside a function.
2284 # And we want to run set -x afterwards to avoid spam, so we cram everything
2285 # in here, and then it will run after this function is done.
2286 PROMPT_COMMAND
='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
2289 PROMPT_COMMAND
=prompt-command
2290 if [[ $TERM == *(screen
*|xterm
*|rxvt
*) ]]; then
2291 trap 'settitle "$BASH_COMMAND"' DEBUG
2295 tx
() { # toggle set -x, and the prompt so it doesnt spam
2296 if [[ $
- == *x
* ]]; then
2305 # show all processes in the network namespace $1.
2306 # blank entries appear to be subprocesses/threads
2310 sudo
find -L /proc
/[1-9]*/task
/*/ns
/net
-samefile /run
/netns
/$netns | cut
-d/ -f5 | \
2312 x
=$
(ps
-w --no-headers -p $l);
2313 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2317 if ! s ip netns list |
grep -Fx nonet
&>/dev
/null
; then
2318 s ip netns add nonet
2320 sudo
-E env
/sbin
/ip netns
exec nonet sudo
-E -u iank
/bin
/bash
2323 m
() { printf "%s\n" "$*"; "$@"; }
2325 # update file. note: duplicated in mail-setup
2327 local tmp tmpdir dest
="$1"
2328 local base
="${dest##*/}"
2329 local dir
="${dest%/*}"
2330 if [[ $dir != "$base" ]]; then
2331 # dest has a directory component
2336 cat >$tmpdir/"$base"
2337 tmp
=$
(rsync
-ic $tmpdir/"$base" "$dest")
2339 printf "%s\n" "$tmp"
2341 if [[ $dest == /etc
/systemd
/system
/* ]]; then
2350 if type -p uprecords
&>/dev
/null
; then
2358 for x
in "$@"; do virsh destroy
"$x"; virsh undefine
"$x"; done
2366 sudo virsh dumpxml
$vm |
sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2367 sed -r "s/listen='[^']+/listen='$ip/"> $t
2368 sudo virsh undefine
$vm
2369 sudo virsh define
$t
2374 vm-set-listen
$1 0.0.0.0
2379 vm-set-listen
$1 127.0.0.1
2383 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2384 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2385 sudo iw dev wls1 scan |
sed -rn "
2386 s/^\Wcapability: (.*)/\1/;Ta;h;b
2387 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2388 # padded to min width of 20
2389 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2393 # Run script by copying it to a temporary location first,
2394 # and changing directory, so we don't have any open
2395 # directories or files that could cause problems when
2412 # spark 1 5 22 13 53
2416 # Copyright (c) Zach Holman, https://zachholman.com
2417 # https://github.com/holman/spark
2419 # As of 2022-10-28, I reviewed github forks that had several newer
2420 # commits, none had anything interesting. I did a little refactoring
2421 # mostly to fix emacs indent bug.
2423 # Generates sparklines.
2426 if [ "X$1" = "X-n" ]; then
2440 # find min/max values
2441 local min
=0xffffffff max
=0
2445 # on Linux (or with bash4) we could use `printf %.0f $n` here to
2446 # round the number but that doesn't work on OS X (bash3) nor does
2447 # `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off
2449 (( n
< min
)) && min
=$n
2450 (( n
> max
)) && max
=$n
2451 numbers
=$numbers${numbers:+ }$n
2455 local ticks
=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █
)
2457 # use a high tick if data is constant
2458 (( min
== max
)) && ticks
=(▅ ▆
)
2461 f
=$
(( ( (max-min
) <<8)/( tc - 1) ))
2466 _spark_echo -n ${ticks[$(( ((($n-$min)<<8)/$f) ))]}
2475 if $use_color && type -p tput &>/dev/null; then
2476 term_bold="$(tput bold)"
2477 term_red="$(tput setaf 1)"
2478 term_green="$(tput setaf 2)"
2479 term_yellow="$(tput setaf 3)"
2480 term_purple="$(tput setaf 5)"
2481 term_nocolor="$(tput sgr0)" # no font attributes
2483 # unused so far. commented for shellcheck
2484 # term_underl="$(tput smul)"
2485 # term_blue="$(tput setaf 4)"
2486 # term_cyan="$(tput setaf 6)"
2488 # Try to keep environment pollution down, EPA loves us.
2489 unset safe_term match_lhs use_color
2494 if [[ $- == *i* ]]; then
2499 if [[ $EUID == 1000 ]]; then
2506 # this needs to come before next ps1 stuff
2507 # this stuff needs bash 4, feb 2009,
2508 # old enough to no longer condition on $BASH_VERSION anymore
2512 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2514 bind -m vi-command B:shell-backward-word
2515 bind -m vi-command W:shell-forward-word
2518 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2519 unset PROMPT_DIRTRIM
2523 # emacs terminal has problems if this runs slowly,
2524 # so I've thrown a bunch of things at the wall to speed it up.
2526 local return=$? # this MUST COME FIRST
2527 local ps_char ps_color
2530 if [[ $HISTFILE ]]; then
2531 history -a # save history
2535 0) ps_color="$term_purple"
2538 *) ps_color="$term_green"
2539 ps_char="$return \\$"
2542 if [[ ! -O . ]]; then # not owner
2543 if [[ -w . ]]; then # writable
2544 ps_color="$term_bold$term_red"
2546 ps_color="$term_bold$term_green"
2550 # faster than sourceing the file im guessing
2551 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2552 eval $(< /dev/shm/iank-status)
2554 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2555 ps_char="@ $ps_char"
2557 # We could test if sudo is active with sudo -nv
2558 # but then we get an email and log of lots of failed sudo commands.
2559 # We could turn those off, but seems better not to.
2560 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2561 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2563 if [[ ! $HISTFILE ]]; then
2564 ps_char="NOHIST $ps_char"
2566 PS1="${PS1%"${PS1#*[wW]}"} $psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2568 # set titlebar. instead, using more advanced
2570 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2572 PROMPT_COMMAND=prompt-command
2574 if [[ $TERM == screen* ]]; then
2575 _title_escape="\033]..2;"
2577 # somme sites recommend this, i dunno what the diff is.
2578 #_title_escape="\033]30;"
2579 _title_escape="\033]0;"
2583 # this makes it so we show the current command if
2584 # one is running, otherwise, show nothing
2586 if [[ $1 == prompt-command ]]; then
2589 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
2590 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2596 # note, this wont work:
2597 # x=$(mktemp); cp a $x
2598 # I havnt figured out why, bigger fish to fry.
2601 # condition from the screen man page i think.
2602 # note: duplicated in tx()
2603 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2604 trap 'settitle "$BASH_COMMAND"' DEBUG
2611 # * stuff that makes sense to be at the end
2617 # shellcheck disable=SC1090
2618 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2620 # I had this idea to start a bash shell which would run an initial
2621 # command passed through this env variable, then continue on
2622 # interactively. But the use case I had in mind went away.
2624 # if [[ $MY_INIT_CMD ]]; then
2625 # "${MY_INIT_CMD[@]}"
2629 # ensure no bad programs appending to this file will have an affect