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 ~
/.iank
/err
]]; then
11 # shellcheck source=/a/bin/errhandle/err
21 # remove all aliases. aliases provided by the system tend to get in the way,
22 # for example, error happens if I try to define a function the same name as an alias
25 # remove gnome keyring warning messages
26 # there is probably a more proper way, but I didnt find any easily on google
27 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
28 #unset GNOME_KEYRING_CONTROL
30 # use extra globing features.
32 # include .files when globbing, but ignore files name . and ..
33 # setting this also sets dotglob.
34 export GLOBIGNORE
="*/.:*/.."
36 # broken with bash_completion package. Saw a bug for this once. dont anymore.
37 # still broken in wheezy
38 # still buggered in latest stable from the web, version 2.1
39 # perhaps its fixed in newer git version, which fails to make for me
40 # this note is from 6-2014.
41 # still broken in flidas.
44 # make tab on an empty line do nothing
45 shopt -s no_empty_cmd_completion
47 # fix spelling errors for cd, only in interactive shell
49 # append history instead of overwritting it
51 # for compatibility, per gentoo/debian bashrc
53 # attempt to save multiline single commands as single history entries.
60 if [[ $RLC_INSIDE_EMACS ]]; then
61 # EMACS is used by bash on startup, but we dont need it anymore.
62 # plus I hit a bug in a makefile which inherited it
64 export RLC_INSIDE_EMACS
67 # scp completion does not work, but this doesnt fix it. todo, figure this out
68 #complete -r scp &> /dev/null
69 # todo, remote file completion fails, figure out how to turn it off
70 export NODE_DISABLE_COLORS
=1
71 # This gets rid of ugly terminal escape chars in node repl
72 # sometime, Id like to have completion working in emacs shell for node
73 # the offending chars can be found in lib/readline.js,
74 # things that do like:
75 # stream.write('\x1b[' + (x + 1) + 'G');
76 # We can remove them and keep readline, for example by doing this
79 # var readline = require('readline');
80 # readline.cursorTo = function(a,b,c) {};
81 # readline.clearScreenDown = function(a) {};
82 # const repl = require('repl');
83 # var replServer = repl.start('');
85 # no prompt, or else readline complete seems to be confused, based
86 # on our column being different? node probably needs to send
87 # different kind of escape sequence that is not ugly. Anyways,
88 # completion doesnt work yet even with the ugly prompt, so whatever
90 export NODE_NO_READLINE
=1
94 # emacs has a different default search path than the info command. This
95 # adds the info defaults to emacs, but not the reverse, because I dun
96 # care much about the cli. The search path is only on the cli if you run
97 # "info xxx", or in emacs if you run '(info xxx)', so not that
98 # important, but might as well fix it.
100 # info info says this path is what was compiled, and its not documented
101 # anywhere. Through source grepping, i found it in filesys.h of the info
102 # source in trisquel flidas.
104 # Traling : means for emacs to add its own stuff on to the end.
106 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
:.
:
108 if [[ $
- == *i
* ]]; then
109 # for readline-complete.el
110 if [[ $RLC_INSIDE_EMACS ]]; then
111 # all for readline-complete.el
113 bind 'set horizontal-scroll-mode on'
114 bind 'set print-completions-horizontally on'
115 bind '"\C-i": self-insert'
118 if [[ $KONSOLE_PROFILE_NAME ]]; then
122 # todo: not sure this works in sakura
124 #bind "\C-w": kill-region
125 # sakura == xterm-256color
127 if [[ $TERM == xterm
* ]]; then
128 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
129 bind '"\e[1;5C": shell-forward-word' 2>/dev
/null
130 bind '"\e[1;5D": shell-backward-word' 2>/dev
/null
132 # make ctrl-backspace work. for konsole, i fixed it through
133 # /home/iank/.local/share/konsole/default.keytab
135 bind '"\eOc": shell-forward-word'
136 bind '"\eOd": shell-backward-word'
138 # i cant remember why i did this, probably to free up some keys to bind
139 # to other things in bash.
140 # other than C-c and C-z, the rest defined by stty -a are, at least in
141 # gnome-terminal, overridden by bash, or disabled by the system
142 stty lnext undef stop undef start undef
148 # history number. History expansion is good.
150 # history file size limit, set to unlimited.
151 # this needs to be different from the default because
152 # default HISTFILESIZE is 500 and could clobber our history
154 # max commands 1 session can append/read from history
156 # the time format display when doing the history command
157 # also, setting this makes the history file record time
158 # of each command as seconds from the epoch
159 HISTTIMEFORMAT
="%Y-%m-%d %I:%M %p "
160 # consecutive duplicate lines dont go in history
161 HISTCONTROL
=ignoredups
162 # works in addition to HISTCONTROL to do more flexible things
163 # it could also do the same things as HISTCONTROL and thus replace it,
164 # but meh. dunno why, but just " *" does glob expansion, so use [ ] to avoid it.
165 HISTIGNORE
='pass *:[ ]*:otp *:oathtool *'
167 export BC_LINE_LENGTH
=0
169 export PROFILE_TASKS_TASK_OUTPUT_LIMIT
=100
171 # note, if I use a machine I dont want files readable by all users, set
172 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
174 # i for insensitive. the rest from
175 # X means dont remove the current screenworth of output upon exit
176 # R means to show colors n things
178 export SYSTEMD_LESS
=$LESS
185 # if someone exported $SOE (stop on error), catch errors.
187 # Note, on debian this results in the following warning when in ssh,
188 # hich I haven't figured out how to fix. It doesn't happen if we source
189 # after the shell has started
191 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
192 # bash: warning: cannot start debugger; debugging mode disabled
194 if [[ -e /a
/bin
/errhandle
/err
]]; then
195 source /a
/bin
/errhandle
/err
199 # based on readme.debian. dunno if this will break on other distros.
200 if [[ -s /usr
/share
/wcd
/wcd-include.sh
]]; then
201 source /usr
/share
/wcd
/wcd-include.sh
204 if [[ -s /a
/bin
/small-misc-bash
/ll-function
]]; then
205 source /a
/bin
/small-misc-bash
/ll-function
206 elif [[ -s ~
/.iank
/ll-function
]]; then
207 # shellcheck source=/a/bin/small-misc-bash/ll-function
208 source ~
/.iank
/ll-function
217 ....
() { c ..
/..
/..
; }
218 .....
() { c ..
/..
/..
/..
; }
219 ......
() { c ..
/..
/..
/..
/..
; }
221 # file cut copy and paste, like the text buffers :)
222 # I havnt tested these.
223 _fbufferinit
() { # internal use
224 ! [[ $my_f_tempdir ]] && my_f_tempdir
=$
(mktemp
-d)
225 rm -rf "${my_f_tempdir:?}"/*
229 cp "$@" "$my_f_tempdir"/
233 mv "$@" "$my_f_tempdir"/
235 fpst
() { # file paste
236 [[ $2 ]] && { echo too many arguments
; return 1; }
238 cp "$my_f_tempdir"/* "$target"
244 read -r ip port
< <(timeout
1 ssh -oBatchMode=yes -oControlMaster=no
-oControlPath=/ -v $1 |
& sed -rn "s/debug1: Connecting to $host \[([^\]*)] port ([0-9]+).*/\1 \2/p")
246 echo "khfix: ssh failed"
249 if [[ $port != 22 ]]; then
250 ip_entry
="[$ip]:$port"
251 host_entry
="[$host]:$port"
256 ssh-keygen
-R "$host_entry" -f $
(readlink
-f ~
/.ssh
/known_hosts
)
257 echo "khfix: removing key for $ip_entry"
258 ssh-keygen
-R "$ip_entry" -f $
(readlink
-f ~
/.ssh
/known_hosts
)
260 khfix
() { # known hosts fix
261 _khfix_common
"$@" ||
return 1
271 x
=$
(readlink
-nf "${1:-$PWD}")
272 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
273 echo -n "$x" | xclip
-selection clipboard
277 ack
() { ack-grep
"$@"; }
286 if type -p wcd
&>/dev
/null
; then
287 if [[ $RLC_INSIDE_EMACS ]]; then
288 c
() { wcd
-c -z 50 -o "$@"; }
290 # lets see what the fancy terminal does from time to time
291 c
() { wcd
-c -z 50 "$@"; }
297 c4
() { c
/var
/log
/exim4
; }
299 caa
() { git commit
--amend --no-edit -a; }
302 # shellcheck disable=SC2033
303 find -L $1 -type f
-not \
( -name .svn
-prune -o -name .git
-prune \
304 -o -name .hg
-prune -o -name .editor-backups
-prune \
305 -o -name .undo-tree-history
-prune \
) \
306 -exec bash
-c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _
{} \
; 2>/dev
/null
310 calc
() { echo "scale=3; $*" |
bc -l; }
311 # no having to type quotes, but also no command history:
315 echo "scale=3; $x" |
bc -l
323 ccat
() { # config cat. see a config without extra lines.
324 grep '^\s*[^;[:space:]#]' "$@"
329 # join options which are continued to multiples lines onto one line
331 while IFS
= read -r line
; do
332 # remove leading spaces/tabs. assumes extglob
333 if [[ $line == "[ ]*" ]]; then
339 elif [[ $line == *=* ]]; then
340 echo "$pastline" >> "$2"
343 pastline
="$pastline $line"
345 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
346 echo "$pastline" >> "$2"
351 # setup for format of postfix, eg:
354 local pastline unified f1 f2
358 _cdiff-prep
"$1" "$f1"
359 _cdiff-prep
"$2" "$f2"
360 cat "$f1" "$f2" |
grep -Po '^[^=]+=' |
sort |
uniq > "$unified"
361 while IFS
= read -r line
; do
362 # the default bright red / blue doesnt work in emacs shell
363 dwdiff
-cblue,red
-A best
-d " ," <(grep "^$line" "$f1" ||
echo ) <(grep "^$line" "$f2" ||
echo ) | colordiff
371 inotifywait
-m "$dir" -e create
-e moved_to |
372 # shellcheck disable=SC2030
373 while read -r filedir _
file; do
376 calc $
((SECONDS
- start
)) / 60
382 # shellcheck disable=SC2032
384 # makes it so chown -R symlink affects the symlink and its target.
385 if [[ $1 == -R ]]; then
387 command chown
-h "$@"
388 command chown
-R "$@"
399 # choose recent directory. cl = cd list
404 complete
-A stopped
-P '"%' -S '"' d
408 diff --strip-trailing-cr -w "$@" # diff content
415 safe_rename
"$x" "$y"
420 command dig +nostats
+nocmd
"$@"
422 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
426 dig +nordflag
"$@" |
sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' |
while read -r l
; do
427 if [[ $l == [^\
;]* ]]; then
431 printf "%s" "$sec" |
sort
438 # compare digs to the 2 servers
439 # usage: digdiff @server1 @server2 DIG_ARGS
440 # note: only the soa master nameserver will respond with
441 # ra "recursive answer" flag. That difference is meaningless afaik.
448 digsort
$s1 "$@" |
tee /tmp
/digdiff
449 diff -u /tmp
/digdiff
<(digsort
$s2 "$@")
453 date "+%A, %B %d, %r" "$@"
456 dus
() { # du, sorted, default arg of
457 du
-sh ${@:-*} |
sort -h
470 printf "%qEOL\n" "${arg}"
471 printf "%s" "${arg}" |
& hexdump -C
474 # echo vars. print var including escapes, etc
480 printf "%qEOL\n" "${!arg}"
481 printf "%s" "${!arg}" |
& hexdump -C
487 [[ ${#@} == 2 ]] ||
{ echo "error: ediff requires 2 arguments"; return 1; }
488 emacs
--eval "(ediff-files \"$1\" \"$2\")"
493 tail -F /var
/log
/exim
4/mainlog
-n 200
496 less /var
/log
/exim
4/mainlog
499 exiqgrep
-i |
while read -r i
; do
500 exim
-Mvh $i; hr
; exim
-Mvb $i; hr
;
501 exigrep
$i /var
/log
/exim
4/mainlog
; hr
506 # shellcheck disable=SC2032
513 # find array. make an array of file names found by find into $x
514 # argument: find arguments
515 # return: find results in an array $x
516 while read -rd ''; do
518 done < <(find "$@" -print0);
521 faf
() { # find all files. use -L to follow symlinks
522 find $@
-not \
( -name .svn
-prune -o -name .git
-prune \
523 -o -name .hg
-prune -o -name .editor-backups
-prune \
524 -o -name .undo-tree-history
-prune \
) -type f
2>/dev
/null
530 s mailq |gr frozen|
awk '{print $3}' |
while read -r id
; do
536 echo -e '\n\n##############################\n'
537 done |
tee -a /tmp
/frozen
541 while read -r line
; do
542 printf '%s\n' "$line"
543 ids
+=($
(printf '%s\n' "$line" |gr frozen|
awk '{print $3}'))
545 echo "sleeping for 2 in case you change your mind"
547 s exim
-Mrm "${ids[@]}"
551 # like -e for functions. returns on error.
552 # at the end of the function, disable with:
554 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
555 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
561 local help="Usage: getdir [--help] PATH
562 Output the directory of PATH, or just PATH if it is a directory."
563 if [[ $1 == --help ]]; then
567 if [[ $# -ne 1 ]]; then
568 echo "getdir error: expected 1 argument, got $#"
575 dir
="$(dirname "$1")"
576 if [[ -d $dir ]]; then
579 echo "getdir error: directory does not exist"
585 git_empty_branch
() { # start an empty git branch. carefull, it deletes untracked files.
586 [[ $# == 1 ]] ||
{ echo 'need a branch name!'; return 1;}
588 root
=$
(gitroot
) ||
return 1 # function to set gitroot
590 git symbolic-ref HEAD refs
/heads
/$1
595 # shellcheck disable=SC2120
597 local help="Usage: gitroot [--help]
598 Print the full path to the root of the current git repo
600 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
601 and works in older versions of git which did not have that."
602 if [[ $1 == --help ]]; then
607 p
=$
(git rev-parse
--git-dir) ||
{ echo "error: not in a git repo" ; return 1; }
608 [[ $p != /* ]] && p
=$PWD
613 # i got an error, gh not found when doing a pull request, it seems like it wants itself in it\'s path.
614 local _oldpath
="$PATH"
615 PATH
="$PATH:$HOME/node_modules/.bin"
621 # quit will prompt if the program crashes.
622 gdb
-ex=r
-ex=quit
--args emacs
"$@"; r
;
626 # kill the emacs daemon
631 grep -iIP --color=auto
"$@"
634 grr
() { # grep recursive
635 # Don't return 1 on nonmatch because this is meant to be
636 # interactive, not in a conditional.
637 if [[ ${#@} == 1 ]]; then
638 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto
"$@" . ||
[[ $?
== 1 ]]
640 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto
"$@" ||
[[ $?
== 1 ]]
644 command rg
-i -M 200 "$@"
647 hr
() { # horizontal row. used to break up output
649 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $
(eval echo "{1..${COLUMNS:-60}}")
653 hrcat
() { local f
; for f
; do [[ -f $f ]] ||
continue; hr
; echo "$f"; cat "$f"; done }
655 # get latest hub and run it
656 # main command to use:
657 # hub pull-request --no-edit
658 # --no-edit means to use the first commit\'s message as the pull request message.
659 # Also, you need to use a feature branch, not master in your fork.
660 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
661 # it\'s at ~/.config/hub
663 local up uptar updir p
664 p
=/github
/hub
/releases
/
665 up
=https
://github.com
/$
(curl
-s https
://github.com
$p|
grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' |
head -n1)
668 if [[ ! -e /a
/opt
/$updir ]]; then
669 rm -rf /a
/opt
/hub-linux-amd64
*
671 tar -C /a
/opt
-zxf /a
/opt
/$uptar
673 s
/a
/opt
/$updir/install
676 # save token across computers
677 if [[ ! -L ~
/.config
/hub
]]; then
678 if [[ -e ~
/.config
/hub
]]; then
679 mv ~
/.config
/hub
/p
/c
/subdir_files
/.config
/
681 if [[ -e /p
/c
/subdir_files
/.config
/hub
]]; then
689 # modified from ~/local/bin/git-completion.bash
690 # other completion commands are mostly taken from bash_completion package
691 complete
-o bashdefault
-o default
-o nospace
-F _git i
2>/dev
/null \
692 || complete
-o default
-o nospace
-F _git i
694 if ! type service
&>/dev
/null
; then
696 echo actually running
: systemctl
$2 $1
712 find -L .
-not \
( -name .svn
-prune -o -name .git
-prune \
713 -o -name .hg
-prune -o -name .editor-backups
-prune \
714 -o -name .undo-tree-history
-prune \
) -iname "*$**" 2>/dev
/null
718 s iptables
-A INPUT
-s $1 -j DROP
723 grep -Il "" "$@" &>/dev
/null
727 journalctl
-n 10000 -f "$@"
729 jr
() { journalctl
"$@" ; }
730 jrf
() { journalctl
-f "$@" ; }
733 if [[ $PWD == /[iap
] ]]; then
734 command ls -A --color=auto
-I lost
+found
"$@"
736 command ls -A --color=auto
"$@"
741 lcn
() { locate -i "*$**"; }
743 lg
() { LC_COLLATE
=C.UTF-8 ll
--group-directories-first; }
745 lt
() { ll
-tr "$@"; }
747 lld
() { ll
-d "$@"; }
749 low
() { # make filenames lowercase, remove bad chars
752 new
="${f,,}" # downcase
753 new
="${new//[^[:alnum:]._-]/_}" # sub bad chars
754 new
="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
755 new
="${new%"${new##*[[:alnum:]]}"}"
756 # remove bad underscores, like __ and _._
757 new
=$
(echo $new |
sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
758 safe_rename
"$f" "$new" ||
return 1
763 lower
() { # make first letter of filenames lowercase.
766 if [[ ${x::1} == [A-Z
] ]]; then
767 y
=$
(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
768 safe_rename
"$x" "$y" ||
return 1
774 k
() { # history search
775 grep -P --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
tail -n 80;
778 ks
() { # history search
779 grep -P --binary-files=text
"$@" ${HISTFILE:-~/.bash_history} |
uniq;
784 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
785 make -qp |
awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
797 mkt
() { # mkdir and touch file
799 mkdir
-p "$(dirname "$path")"
803 # shellcheck disable=SC2032
804 mkdir
() { command mkdir
-p "$@"; }
807 # shellcheck disable=SC2024
808 sudo
tee -a /var
/log
/exim
4/paniclog-archive
</var
/log
/exim
4/paniclog
; sudo truncate
-s0 /var
/log
/exim
4/paniclog
811 p8
() { ping 8.8.8.8; }
812 p6
() { ping6
2001:4860:4860::8888; }
814 pkx
() { # package extract
815 local pkg cached tmp f
818 # shellcheck disable=SC2012
819 cached
=$
(ls -t /var
/cache
/apt
/archives
/$pkg* |
tail -n1 2>/dev
/null
)
820 if [[ $cached ]]; then
823 aptitude download
$pkg ||
return 1
825 tmp
=(*); f
=${tmp[0]} # only 1 expected
833 pid
=($
(pgrep
-f "$*"))
836 # shellcheck disable=SC2128
842 0) echo "no pid found" ;;
851 help="Usage: psg [--help] GREP_ARGS
852 grep ps and output in a nice format"
853 if [[ $1 == --help ]]; then
858 # final grep is because some commands tend to have a lot of trailing spaces
859 y
=$
(echo "$x" |
grep -iP "$@" |
grep -o '.*[^ ]') ||
:
861 echo "$x" |
head -n 1
866 pubip
() { curl
-4s https
://icanhazip.com
; }
867 pubip6
() { curl
-6s https
://icanhazip.com
; }
868 whatismyip
() { pubip
; }
873 # -t = print pronunciation
875 for (( i
=0; i
<10; i
++ )); do
876 shuf
-n3 /usr
/share
/hunspell
/en_US.dic |
sed 's,/.*,,' |
paste -sd .
-
882 # -M CLN = use Caps, Lowercase, Numbers
884 # -a 1 = use random instead of pronounceable algorithm
885 apg
-m 50 -x 70 -n 1 -a 1 -M CLN
889 q
() { # start / launch a program in the backround and redir output to null
893 # shellcheck disable=SC2120
895 history -a # save history
896 trap ERR
# this avoids a segfault
898 # i had this redir, not sure why
899 # exit "$@" 2>/dev/null
903 # rsync, root is required to keep permissions right.
904 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
905 # --no-times --delete
906 # basically, make an exact copy, use checksums instead of file times to be more accurate
907 rsync
-ahvic --delete "$@"
910 # like rlu, but dont delete files on the target end which
911 # do not exist on the original end.
914 complete
-F _rsync
-o nospace rld rl rlt
917 # rl without preserving modification time.
918 rsync
-ahvic --delete --no-t "$@"
921 rlu
() { # [OPTS] HOST PATH
922 # eg. rlu -opts frodo /testpath
923 # relative paths will expanded with readlink -f.
924 opts
=("${@:1:$#-2}") # 1 to last -2
925 path
="${*:$#}" # last
926 host="${*:$#-1:1}" # last -1
927 if [[ $path == .
* ]]; then
928 path
=$
(readlink
-f $path)
930 # rync here uses checksum instead of time so we dont mess with
931 # unison relying on time as much. g is for group, same reason
932 # to keep up with unison.
933 s rsync
-rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
937 ssh fencepost
head -n 300 /gd
/gnuorg
/EventAndTravelInfo
/rms-current-trips.txt |
less
942 # I use a function because otherwise we cant use in a script,
943 # cant assign to variable.
945 # note: gksudo is recommended for X apps because it does not set the
946 # home directory to the same, and thus apps writing to ~ fuck things up
947 # with root owned files.
949 if [[ $EUID != 0 ||
$1 == -* ]]; then
950 # shellcheck disable=SC2034
951 SUDOD
="$PWD" sudo
-i "$@"
957 safe_rename
() { # warn and dont rename if file exists.
958 # mv -n exists, but it\'s silent
959 if [[ $# != 2 ]]; then
960 echo safe_rename error
: $# args
, need
2 >2
963 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
964 if [[ -e $2 ||
-L $2 ]]; then
965 echo "Cannot rename $1 to $2 as it already exists."
973 sb
() { # sudo bash -c
974 # use sb instead of s is for sudo redirections,
975 # eg. sb 'echo "ok fine" > /etc/file'
979 complete
-F _root_command s sb
983 local s
; [[ $EUID != 0 ]] && s
=s
984 if type -p systemctl
&>/dev
/null
; then
990 # like restart, but do nothing if its not already started
993 if [[ $
(s systemctl
--no-pager show
-p ActiveState
$service ) == ActiveState
=active
]]; then
994 systemctl restart
$service
998 setini
() { # set a value in a .ini style file
999 key
="$1" value
="$2" section
="$3" file="$4"
1000 if [[ -s $file ]]; then
1001 sed -ri -f - "$file" <<EOF
1002 # remove existing keys
1003 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1005 /^\s*\[$section\]/a $key=$value
1006 # from section to eof, do nothing
1007 /^\s*\[$section\]/,\$b
1008 # on the last line, if we haven't found section yet, add section and key
1020 sgo
() { # service go
1022 ser restart
$service ||
return 1
1023 if type -p systemctl
&>/dev
/null
; then
1029 systemctl list-unit-files | rg
"$@"
1034 # 2086: unquoted $var
1035 # 2046: unquoted $(cmd)
1036 # 2068: Double quote array expansions to avoid re-splitting elements.
1037 # 2119: Functions with optional args get bad warnings when none are passed.
1038 # 2033: too many false positives for thing that will never work, passing shell function to find.
1039 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1040 shellcheck
-x -e 2086,2046,2068,2119,2033 "$@"
1041 # had this before. not sure what it is 2119
1046 # log with script. timing is $1.t and script is $1.s
1047 # -l to save to ~/typescripts/
1048 # -t to add a timestamp to the filenames
1049 local logdir do_stamp arg_base
1050 (( $# >= 1 )) ||
{ echo "arguments wrong"; return 1; }
1053 while getopts "lt" option
1056 l
) arg_base
=$logdir ;;
1057 t
) do_stamp
=true
;;
1060 shift $
((OPTIND
- 1))
1062 [[ -e $logdir ]] || mkdir
-p $logdir
1063 $do_stamp && arg_base
+=$
(date +%F.
%T
%z
)
1064 script -t $arg_base.s
2> $arg_base.t
1066 splay
() { # script replay
1067 #logRoot="$HOME/typescripts/"
1068 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1069 scriptreplay
"$1.t" "$1.s"
1073 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1074 if [[ $# == 0 ]]; then
1075 sudo
-E bash
-c -l "$(history -p '!!')"
1077 echo this
command redos last
history item. no argument is accepted
1082 # with -ll, less secure but faster.
1083 command srm
-ll "$@"
1088 ssh $1 /tmp
/${2##*/} $
(printf "%q\n" "${@:2}")
1100 tclock
() { # terminal clock
1105 # this goes to full width
1106 #len=${1:-$((COLUMNS -7))}
1109 if (( x
== len
)); then
1111 d
="$(date +%l:%_M) "
1114 d
=$
(date +%l
:%M
:%_S
)
1118 for ((i
=0; i
<x
; i
++)); do
1119 if (( i
% 6 )); then
1137 # test existence / exists
1140 [[ -e "$x" ||
-L "$x" ]] || ret
=1
1146 tx
() { # toggle set -x, and the prompt so it doesnt spam
1147 if [[ $
- == *x
* ]]; then
1149 PROMPT_COMMAND
=prompt-command
1150 # disabled due to issue on stretch, running ll we get error. something
1151 # about the DEBUG trap is broken
1152 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1153 # trap 'settitle "$BASH_COMMAND"' DEBUG
1156 # normally, i would just execute these commands in the function.
1157 # however, DEBUG is not inherited, so we need to run it outside a function.
1158 # And we want to run set -x afterwards to avoid spam, so we cram everything
1159 # in here, and then it will run after this function is done.
1160 #PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "; set -x'
1162 unset PROMPT_COMMAND
1169 # show all processes in the network namespace $1.
1170 # blank entries appear to be subprocesses/threads
1174 s
find -L /proc
/[1-9]*/task
/*/ns
/net
-samefile /run
/netns
/$netns | cut
-d/ -f5 | \
1176 x
=$
(ps
-w --no-headers -p $l);
1177 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1181 m
() { printf "%s\n" "$*"; "$@"; }
1185 for x
in "$@"; do virsh destroy
"$x"; virsh undefine
"$x"; done
1193 s virsh dumpxml
$vm |
sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1194 sed -r "s/listen='[^']+/listen='$ip/"> $t
1195 s virsh undefine
$vm
1201 vm-set-listen
$1 0.0.0.0
1206 vm-set-listen
$1 127.0.0.1
1212 # temporary variables to test colorization
1213 # some copied from gentoo /etc/bash/bashrc,
1215 # dircolors --print-database uses its own built-in database
1216 # instead of using /etc/DIR_COLORS. Try to use the external file
1217 # first to take advantage of user additions.
1218 safe_term
=${TERM//[^[:alnum:]]/?} # sanitize TERM
1220 [[ -f ~
/.dir_colors
]] && match_lhs
="${match_lhs}$(<~/.dir_colors)"
1221 [[ -f /etc
/DIR_COLORS
]] && match_lhs
="${match_lhs}$(</etc/DIR_COLORS)"
1222 [[ -z ${match_lhs} ]] \
1223 && type -P dircolors
>/dev
/null \
1224 && match_lhs
=$
(dircolors
--print-database)
1225 # test if our $TERM is in the TERM values in dircolor
1226 [[ $
'\n'${match_lhs} == *$
'\n'"TERM "${safe_term}* ]] && use_color
=true
1229 if ${use_color} && [[ $
- == *i
* ]]; then
1231 term_bold
="$(tput bold)"
1232 term_red
="$(tput setaf 1)"
1233 term_green
="$(tput setaf 2)"
1234 term_yellow
="$(tput setaf 3)"
1235 term_purple
="$(tput setaf 5)"
1236 term_nocolor
="$(tput sgr0)" # no font attributes
1238 # unused so far. commented for shellcheck
1239 # term_underl="$(tput smul)"
1240 # term_blue="$(tput setaf 4)"
1241 # term_cyan="$(tput setaf 6)"
1244 # Try to keep environment pollution down, EPA loves us.
1245 unset safe_term match_lhs use_color
1250 if [[ $
- == *i
* ]]; then
1252 # this needs to come before next ps1 stuff
1253 # this stuff needs bash 4, feb 2009,
1254 # old enough to no longer condition on $BASH_VERSION anymore
1258 if [[ $
- == *i
* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1260 bind -m vi-command B
:shell-backward-word
1261 bind -m vi-command W
:shell-forward-word
1264 if [[ $SSH_CLIENT ||
$SUDO_USER ]]; then
1268 # emacs terminal has problems if this runs slowly,
1269 # so I've thrown a bunch of things at the wall to speed it up.
1271 local return=$?
# this MUST COME FIRST
1272 local ps_char ps_color
1275 history -a # save history
1278 0) ps_color
="$term_purple"
1281 1) ps_color
="$term_green"
1282 ps_char
="$return \\$"
1284 *) ps_color
="$term_yellow"
1285 ps_char
="$return \\$"
1288 if [[ ! -O .
]]; then # not owner
1289 if [[ -w .
]]; then # writable
1290 ps_color
="$term_bold$term_red"
1292 ps_color
="$term_bold$term_green"
1296 # faster than sourceing the file im guessing
1297 if [[ -e /dev
/shm
/iank-status
]]; then
1298 eval $
(< /dev
/shm
/iank-status
)
1300 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1301 ps_char
="@ $ps_char"
1303 PS1
="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1305 PROMPT_COMMAND
=prompt-command
1308 if [[ $TERM == screen
* ]]; then
1309 local title_escape
="\033]..2;"
1311 local title_escape
="\033]0;"
1313 if [[ $0 != prompt-command
]]; then
1314 echo -ne "$title_escape$USER@$HOSTNAME ${PWD/#$HOME/~} "
1321 # condition from the screen man page i think.
1322 # note: duplicated in tx()
1323 # disabled. see note in tx
1324 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1325 # trap 'settitle "$BASH_COMMAND"' DEBUG
1332 # * stuff that makes sense to be at the end
1338 # shellcheck disable=SC1090
1339 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
1342 # ensure no bad programs appending to this file will have an affect