1 # Copyright (C) 2016 Ian Kelling
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 # redirect output to log file. this doesn't work. todo figure out why
18 #exec 1>>/a/tmp/bashlog
19 #exec 2>>/a/tmp/bashlog
22 # By default this file is sourced for ALL ssh commands. This is wonky.
23 # Normally, this file is not sourced when a script is run, but we can
24 # override that by having #!/bin/bash -l. I want something similar for ssh
25 # commands. when a local script runs an ssh command, this file should not be
26 # sourced by default, but we should be able to override that.
28 # so here we test for conditions of a script under ssh and return if so. To test
29 # for an overriding condition, we have a few options. one is to use an
30 # environment variable. env variables sent across ssh are strictly limited. ssh
31 # -t which sets $SSH_TTY, but within a script that won't work because tty
32 # allocation will fail. We could override an obscure unused LC_var, like
33 # telephone, but I don't want to run into some edge case where that messes
34 # things up. we could transfer a file which we could test for, but I can't think
35 # of a way to make that inherently limited to a single ssh command. I choose to
36 # set SendEnv and AcceptEnv ssh config vars to allow the environment variable
37 # BASH_LOGIN_SHELL to propagate across ssh.
39 # assume we want ssh commands to source this file if we are sourcing it,
40 # and we haven't specified otherwise already
41 [[ ! $BASH_LOGIN_SHELL ]] && export BASH_LOGIN_SHELL=true
43 # first conditions show that we are an ssh command without an interactive shell
44 if [[ $SSH_CONNECTION ]] \
48 && [[ ! $BASH_LOGIN_SHELL == true ]]; then
56 # note, to catch errors in functions but not outside, do:
59 # trap 'trap ERR' RETURN
71 # remove all aliases. aliases provided by the system tend to get in the way,
72 # for example, error happens if I try to define a function the same name as an alias
75 # remove gnome keyring warning messages
76 # there is probably a more proper way, but I didn't find any easily on google
77 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
78 #unset GNOME_KEYRING_CONTROL
80 # use extra globing features.
82 # include .files when globbing, but ignore files name . and ..
83 # setting this also sets dotglob
84 export GLOBIGNORE=*/.:*/..
86 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
87 # still broken in wheezy
88 # still buggered in latest stable from the web, version 2.1
89 # perhaps its fixed in newer git version, which fails to make for me
90 # this note is from 6-2014.
91 # Also, enabling this before sourcing .bashrc makes PATH be empty.
94 # make tab on an empty line do nothing
95 shopt -s no_empty_cmd_completion
98 # http://bash-completion.alioth.debian.org/
99 # might be sourced by the system already, but I've noticed it not being sourced before
100 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
101 . /usr/share/bash-completion/bash_completion
105 # fix spelling errors for cd, only in interactive shell
107 # append history instead of overwritting it
109 # for compatibility, per gentoo/debian bashrc
110 shopt -s checkwinsize
111 # attempt to save multiline single commands as single history entries.
117 if [[ $INSIDE_EMACS ]]; then
118 # EMACS is used by bash on startup, but we don't need it anymore.
119 # plus I hit a bug in a makefile which inherited it
124 # scp completion does not work, but this doesn't fix it. todo, figure this out
125 complete -r scp &> /dev/null
126 # todo, remote file completion fails, figure out how to turn it off
127 export NODE_DISABLE_COLORS=1
128 # This get's rid of ugly terminal escape chars in node repl
129 # sometime, I'd like to have completion working in emacs shell for node
130 # the offending chars can be found in lib/readline.js,
131 # things that do like:
132 # stream.write('\x1b[' + (x + 1) + 'G');
133 # We can remove them and keep readline, for example by doing this
135 #!/usr/bin/env nodejs
136 # var readline = require('readline');
137 # readline.cursorTo = function(a,b,c) {};
138 # readline.clearScreenDown = function(a) {};
139 # const repl = require('repl');
140 # var replServer = repl.start('');
142 # no prompt, or else readline complete seems to be confused, based
143 # on our column being different? node probably needs to send
144 # different kind of escape sequence that is not ugly. Anyways,
145 # completion doesn't work yet even with the ugly prompt, so whatever
147 export NODE_NO_READLINE=1
152 if [[ $- == *i* ]]; then
153 # for readline-complete.el
154 if [[ $INSIDE_EMACS ]]; then
155 # all for readline-complete.el
157 bind 'set horizontal-scroll-mode on'
158 bind 'set print-completions-horizontally on'
159 bind '"\C-i": self-insert'
161 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
162 if [[ $TERM == "xterm" ]]; then
163 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
164 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
166 bind '"\eOc": shell-forward-word'
167 bind '"\eOd": shell-backward-word'
169 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
170 # gnome-terminal, overridden by bash, or disabled by the system
171 stty werase undef lnext undef stop undef start undef
178 # history number. History expansion is good.
180 # history file size limit, set to unlimited.
181 # this needs to be different from the default because
182 # default HISTFILESIZE is 500 and could clobber our history
184 # max commands 1 session can append/read from history
186 # my own history size limit based on lines
187 HISTFILELINES=1000000
189 # the time format display when doing the history command
190 # also, setting this makes the history file record time
191 # of each command as seconds from the epoch
192 HISTTIMEFORMAT="%I:%M %p %m/%d "
193 # consecutive duplicate lines don't go in history
194 HISTCONTROL=ignoredups
195 # works in addition to HISTCONTROL to do more flexible things
196 # it could also do the same things as HISTCONTROL and thus replace it,
200 export BC_LINE_LENGTH=0
203 # note, if I use a machine I don't want files readable by all users, set
204 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
213 for _x in /a/bin/distro-functions/src/* /a/bin/!(githtml)/*-function?(s); do
217 # so I can share my bashrc
218 for x in /a/bin/bash_unpublished/!(.#*); do source $x; done
219 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
220 source /a/bin/log-quiet/logq-function
222 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
223 # todo, these need to be renamed to be less generic.
224 # sync overrode something else useful
225 #path_add $HOME/bin/bash-programs-by-ian/utils
232 # very few aliases, functions are always preferred.
235 if [[ $OS == Windows_NT ]]; then
236 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
238 alias j='command cygpath'
239 alias t='command cygstart'
240 alias cygstart='echo be quick, use the alias "t" instead :\)'
241 alias cygpath='echo be quick, use the alias "j" instead :\)'
246 # keep this in mind? good for safety.
251 # remove any default aliases for these
252 unalias ls ll grep &>/dev/null ||:
263 #####################
265 #####################
270 # file cut copy and paste, like the text buffers :)
271 # I havn't tested these.
272 _fbufferinit() { # internal use by
273 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
274 rm -rf "$my_f_tempdir"/*
278 cp "$@" "$my_f_tempdir"/
282 mv "$@" "$my_f_tempdir"/
284 fpst() { # file paste
285 [[ $2 ]] && { echo too many arguments; return 1; }
287 cp "$my_f_tempdir"/* "$target"
292 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
296 # join options which are continued to multiples lines onto one line
298 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
299 # remove leading spaces/tabs. assumes extglob
300 if [[ $line == "[ ]*" ]]; then
306 elif [[ $line == *=* ]]; then
307 echo "$pastline" >> "$2"
310 pastline="$pastline $line"
313 echo "$pastline" >> "$2"
318 ssh-keygen -R $h -f $(readlink -f ~/.ssh/known_hosts)
319 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
320 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
322 khfix() { # known hosts fix
335 ack() { ack-grep "$@"; }
338 local startdir="$PWD"
341 ssh $x mkdir -p bin/distro-functions/src
342 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
345 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
347 tar cz * | ssh $x tar xz
352 caa() { git commit --amend --no-edit -a; }
354 calc() { echo "scale=3; $*" | bc -l; }
355 # no having to type quotes, but also no command history:
359 echo "scale=3; $x" | bc -l
366 ccat () { # config cat. see a config without extra lines.
367 grep '^\s*[^[:space:]#]' "$@"
372 # setup for format of postfix, eg:
376 local unified="$(mktemp)"
379 _cdiff-prep "$1" "$f1"
380 _cdiff-prep "$2" "$f2"
381 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
382 while IFS= read -r line; do
383 # the default bright red / blue doesn't work in emacs shell
384 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
391 cp /a/bin/data/COPYING "$@"
393 cp /a/bin/data/COPYING .
399 cp /a/bin/data/LICENSE "$@"
401 cp /a/bin/data/LICENSE .
405 # makes it so chown -R symlink affects the symlink and its target.
406 if [[ $1 == -R ]]; then
408 command chown -h "$@"
409 command chown -R "$@"
420 complete -A stopped -P '"%' -S '"' d
422 dat() { # do all tee, for more complex scripts
423 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
428 for host in x2 tp treetowl; do
434 diff --strip-trailing-cr -w "$@" # diff content
437 debian_pick_mirror () {
438 # netselect-apt finds a fast mirror.
439 # but we need to replace the mirrors ourselves,
440 # because it doesn't do that. best it can do is
441 # output a basic sources file
442 # here we get the server it found, get the main server we use
443 # then substitute all instances of one for the other in the sources file
444 # and backup original to /etc/apt/sources.list-original.
445 # this is idempotent. the only way to identify debian sources is to
446 # note the original server, so we put it in a comment so we can
448 local file=$(mktemp -d)/f # safe way to get file name without creating one
449 sudo netselect-apt -o "$file" || return 1
450 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
451 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
452 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
460 safe_rename "$x" "$y"
465 date "+%A, %B %d, %r" "$@"
469 du -sh ${@:-*} | sort -h
478 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
479 emacs --eval "(ediff-files \"$1\" \"$2\")"
483 envload() { # load environment from a previous: export > file
484 local file=${1:-$HOME/.${USER}_env}
485 eval "$(export | sed 's/^declare -x/export -n/')"
486 while IFS= read -r line; do
487 # declare -x makes variables local to a function
488 eval ${line/#declare -x/export}
494 # find array. make an array of file names found by find into $x
495 # argument: find arguments
496 # return: find results in an array $x
497 while read -rd ''; do
499 done < <(find "$@" -print0);
504 if type -P firefox &>/dev/null; then
514 firefox -P alt "$@" >/dev/null 2>&1
520 local dname="${PWD##*/}"
521 local m="/a/tmp/$dname-missing"
522 local d="/a/tmp/$dname-diff"
523 [[ -e $d ]] && rm "$d"
524 [[ -e $m ]] && rm "$m"
527 while read -r line; do
529 if [[ -e "$fsfile" ]]; then
530 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
536 done < <(find -type f )
539 (( msize <= 100 )) && cat $m
543 # expected output, with different tmp dirs
544 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
545 # /a/tmp/tmp.qLDkYxBYPM-missing
554 echo different > $x/c/d
559 # test whether missing files were renamed, generally for use with fsdiff
560 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
561 # echos non-renamed files
565 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
567 while read -r line; do
568 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
570 for x in "${sums[@]}"; do
571 if [[ $missing_sum == "$x" ]]; then
576 $renamed || echo "$line"
582 command feh -FzZ "$@"
586 # like -e for functions. returns on error.
587 # at the end of the function, disable with:
589 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
590 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
597 firefox -P default "$@" >/dev/null 2>&1
601 local help="Usage: getdir [--help] PATH
602 Output the directory of PATH, or just PATH if it is a directory."
603 if [[ $1 == --help ]]; then
607 if [[ $# -ne 1 ]]; then
608 echo "getdir error: expected 1 argument, got $#"
614 local dir="$(dirname "$1")"
615 if [[ -d $dir ]]; then
618 echo "getdir error: directory does not exist"
624 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
625 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
627 gitroot || return 1 # function to set gitroot
628 builtin cd "$gitroot"
629 git symbolic-ref HEAD refs/heads/$1
635 local help="Usage: gitroot [--help]
636 Print the full path to the root of the current git repo
638 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
639 and works in older versions of git which did not have that."
640 if [[ $1 == --help ]]; then
644 local p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
645 [[ $p != /* ]] && p=$PWD
650 grep -iIP --color=auto "$@"
654 if [[ ${#@} == 1 ]]; then
655 grep -riIP --color=auto "$@" .
657 grep -riIP --color=auto "$@"
661 hl() { # history limit. Write extra history to archive file.
662 # todo: this is not working or not used currently
663 local max_lines linecount tempfile prune_lines x
664 local harchive="${HISTFILE}_archive"
665 for x in "$HISTFILE" "$harchive"; do
666 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
667 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
668 echo "error in hl: history file \$x:$x no good"
672 history -a # save history
673 max_lines=$HISTFILELINES
674 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
675 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
676 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
677 if (($linecount > $max_lines)); then
678 prune_lines=$(($linecount - $max_lines))
679 head -n $prune_lines "$HISTFILE" >> "$harchive" \
680 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
684 hr() { # horizontal row. used to break up output
685 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS)
691 # modified from ~/local/bin/git-completion.bash
692 # other completion commands are mostly taken from bash_completion package
693 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
694 || complete -o default -o nospace -F _git i
696 if ! type service &>/dev/null; then
698 echo actually running: systemctl $2 $1
711 find -L . -iname "*$**" 2>/dev/null
715 if [[ $OS == Windows_NT ]]; then
726 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
731 if type gvfs-open &> /dev/null ; then
736 # another alternative is run-mailcap
743 grep -Il "" "$@" &>/dev/null
748 if [[ $PWD == /[iap] ]]; then
749 command ls -A --color=auto -I lost+found "$@"
751 command ls -A --color=auto "$@"
756 lcn() { locate -i "*$**"; }
758 lld() { ll -d "$@"; }
760 low() { # make filenames all lowercase
763 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
764 [[ $y != $x ]] && mv "$x" "$y"
771 lower() { # make first letter of filenames lowercase.
774 if [[ ${x::1} == [A-Z] ]]; then
775 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
776 safe_rename "$x" "$y"
782 k() { # history search
783 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40;
788 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
789 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
798 mkdir() { command mkdir -p "$@"; }
806 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
807 pactl load-module module-ladspa-sink sink_name=Karaoke master=alsa_output.usb-Audioengine_Audioengine_D1-00.analog-stereo plugin=karaoke_1409 label=karaoke control=-30
811 pfind() { #find *$1* in $PATH
812 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
814 IFS=: pathArray=($PATH); unset IFS
815 find "${pathArray[@]}" -iname "*$1*"
819 # trash-restore lists everything that has been trashed at or below CWD
820 # This picks out files just in CWD, not subdirectories,
821 # which also match grep $1, usually use $1 for a time string
822 # which you get from running restore-trash once first
825 # last condition is to not ask again for ones we skipped
826 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
827 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
828 name="$(echo "$name" | head -n $nth | tail -n 1 )"
829 read -p "$name [Y/n] " ask
830 if [[ ! $ask || $ask == [Yy] ]]; then
831 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
832 echo $x | restore-trash > /dev/null
833 elif [[ $ask == [Nn] ]]; then
845 [[ $EUID == 0 ]] || s=s
846 $s postconf -ev "${MAPFILE[@]}"
850 rld /a/h/_site/ li:/var/www/iankelling.org/html
853 pubip() { curl -4s https://icanhazip.com; }
854 whatismyip() { pubip; }
862 q() { # start / launch a program in the backround and redir output to null
867 exit "$@" 2>/dev/null
870 rbpipe() { rbt post -o --diff-filename=- "$@"; }
871 rbp() { rbt post -o "$@"; }
874 # rsync, root is required to keep permissions right.
875 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
876 # --no-times --delete
877 # basically, make an exact copy, use checksums instead of file times to be more accurate
878 rsync -ahvic --delete "$@"
881 # like rlu, but don't delete files on the target end which
882 # do not exist on the original end.
885 complete -F _rsync -o nospace rld rl rlt
888 # rl without preserving modification time.
889 rsync -ahvic --delete --no-t "$@"
892 rlu() { # [OPTS] HOST PATH
893 # eg rlu -opts frodo testpath
894 # useful for selectively sending dirs which have been synced with unison,
895 # where the path is the same on both hosts.
896 opts=("${@:1:$#-2}") # 1 to last -2
897 path="${@:$#}" # last
898 host="${@:$#-1:1}" # last -1
899 if [[ $path == .* ]]; then echo error: need absolut path; return 1; fi
900 # rync here uses checksum instead of time so we don't mess with
901 # unison relying on time as much. g is for group, same reason
902 # to keep up with unison.
903 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
907 rspicy() { # usage: HOST DOMAIN
908 # connect to spice vm remote host. use vspicy for local host
909 local port=$(ssh $1<<EOF
910 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
911 sed -rn "s/.*port='([0-9]+).*/\1/p"
917 echo "error: no port found. check that the domain is running."
923 # I use a function because otherwise we can't use in a script,
924 # can't assign to variable.
926 # note: gksudo is recommended for X apps because it does not set the
927 # home directory to the same, and thus apps writing to ~ fuck things up
928 # with root owned files.
930 if [[ $EUID != 0 || $1 == -* ]]; then
931 SUDOD="$PWD" sudo -i "$@"
938 if [[ $# != 2 ]]; then
939 echo safe_rename error: $# args, need 2 >2
941 elif [[ $1 != $2 ]]; then
943 echo Cannot rename "$1" to "$2" as it already exists.
951 sb() { # sudo bash -c
952 # use sb instead of s is for sudo redirections,
953 # eg. sb 'echo "ok fine" > /etc/file'
957 complete -F _root_command s sb
961 local s; [[ $EUID != 0 ]] && s=sudo
962 if type -p systemctl &>/dev/null; then
972 if type -p systemctl &>/dev/null; then
979 # 2086 = unquoted $var
980 # 2046 = unquoted $(cmd)
981 # i had -x as an arg, but debian testing(stretch) doesn't support it
982 shellcheck -e 2086,2046,2068,2006,2119 "$@"
987 # log with script. timing is $1.t and script is $1.s
988 # -l to save to ~/typescripts/
989 # -t to add a timestamp to the filenames
990 local logdir do_stamp arg_base
991 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
994 while getopts "lt" option
997 l ) arg_base=$logdir ;;
1001 shift $(($OPTIND - 1))
1003 [[ -e $logdir ]] || mkdir -p $logdir
1004 $do_stamp && arg_base+=$(date +%F.%T%z)
1005 script -t $arg_base.s 2> $arg_base.t
1007 splay() { # script replay
1008 #logRoot="$HOME/typescripts/"
1009 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1010 scriptreplay "$1.t" "$1.s"
1014 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1015 if [[ $# == 0 ]]; then
1016 sudo -E bash -c -l "$(history -p '!!')"
1018 echo this command redos last history item. no argument is accepted
1023 # with -ll, less secure but faster.
1024 command srm -ll "$@"
1029 ssh $1 /tmp/${2##*/} "${@:2}"
1035 if type -t trash-put >/dev/null; then
1036 # skip args that don't exist, or else trash-put will have an error
1038 if [[ -e $x || -L $x ]]; then
1042 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1053 # this goes to full width
1054 #len=${1:-$((COLUMNS -7))}
1057 if (( x == len )); then
1059 d="$(date +%l:%_M) "
1062 d=$(date +%l:%M:%_S)
1066 for ((i=0; i<x; i++)); do
1067 if (( i % 6 )); then
1085 # test existence / exists
1088 [[ -e "$x" || -L "$x" ]] || ret=1
1095 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1098 ts() { # start editing a new file
1099 [[ $# != 1 ]] && echo "I need a filename." && return 1
1101 if [[ $- != *i* ]]; then
1104 if [[ $1 == *.c ]]; then
1105 e '#include <stdio.h>' >"$1"
1106 e '#include <stdlib.h>' >>"$1"
1107 e 'int main(int argc, char * argv[]) {' >>"$1"
1108 e ' printf( "hello world\n");' >>"$1"
1109 e ' return 0;' >>"$1"
1111 e "${1%.c}: $1" > Makefile
1112 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1113 e "#!/bin/bash" >run.sh
1114 e "./${1%.c}" >>run.sh
1116 elif [[ $1 == *.java ]]; then
1117 e "public class ${1%.*} {" >"$1"
1118 e ' public static void main(String[] args) {' >>"$1"
1119 e ' System.out.println("Hello, world!");' >>"$1"
1123 echo "#!/bin/bash" > "$1"
1126 [[ $quiet ]] || g "$1"
1132 local dir="$(dirname "$1")"
1133 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1139 tx() { # toggle set -x, and the prompt so it doesn't spam
1140 if [[ $- == *x* ]]; then
1142 PROMPT_COMMAND=prompt_command
1144 unset PROMPT_COMMAND
1151 [[ $1 ]] || { e "$0: error, expected cmd to run"; return 1; }
1152 # manually run vpn so it stays within a network namespace,
1153 # until I get it all wired up with systemd.
1155 pid=$(< /run/openvpn/client.pid)
1158 if [[ -e /proc/$pid ]]; then
1162 s rm -f /run/openvpn/client.pid
1165 $vpn_on || s ip netns exec vpn /usr/sbin/openvpn --daemon ovpn --config /etc/openvpn/client.conf --cd /etc/openvpn --writepid /run/openvpn/client.pid
1166 gksudo -- ip netns exec vpn gksudo -u ${SUDO_USER:-$USER} "$@"
1170 vc transmission-gtk&
1172 while ((i < 10)); do
1173 tun_ip=$(s ip netns exec vpn ip a show dev tun0 | sed -rn 's/^ *inet (10\.8\.\S+).*/\1/p')
1174 [[ ! $tun_ip ]] || break
1177 echo "$0: tun_ip=$tun_ip"
1178 [[ $tun_ip ]] || { e "$0: error: no tun0 addr found"; return 1; }
1179 ssh dopub bash <<EOF
1181 rule="-A PREROUTING -i eth0 -p tcp -m tcp --dport 63324 -j DNAT --to-destination $tun_ip:63324"
1183 while read -r line; do
1184 if [[ \$line == \$rule ]] && ! \$found; then
1187 iptables -t nat -D \${line#-A}
1189 done < <(iptables -t nat -S | grep -E -- '--dport\s+63324')
1190 \$found || iptables -t nat \$rule
1195 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1202 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1203 sed -r "s/listen='[^']+/listen='$ip/"> $t
1204 s virsh undefine $vm
1210 vm-set-listen $1 0.0.0.0
1215 vm-set-listen $1 127.0.0.1
1219 s systemctl start openvpn@client&
1220 journalctl --unit=openvpn@client -f -n0
1225 s systemctl stop openvpn@client
1236 vspicy() { # usage: VIRSH_DOMAIN
1237 # connect to vms made with virt-install
1238 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1239 sed -r "s/.*port='([0-9]+).*/\1/")
1243 whatismyip() { curl ipecho.net/plain ; echo; }
1246 #############################
1247 ######### misc stuff ########
1248 #############################
1250 if [[ $- == *i* ]]; then
1251 # commands to run when bash exits normally
1252 trap "hl; _smh" EXIT
1256 # temporary variables to test colorization
1257 # some copied from gentoo /etc/bash/bashrc,
1259 # dircolors --print-database uses its own built-in database
1260 # instead of using /etc/DIR_COLORS. Try to use the external file
1261 # first to take advantage of user additions.
1262 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1264 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1265 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1266 [[ -z ${match_lhs} ]] \
1267 && type -P dircolors >/dev/null \
1268 && match_lhs=$(dircolors --print-database)
1269 # test if our $TERM is in the TERM values in dircolor
1270 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1273 if ${use_color} && [[ $- == *i* ]]; then
1275 if [[ $XTERM_VERSION == Cygwin* ]]; then
1279 underl) echo -n $'\E[4m' ;;
1280 bold) echo -n $'\E[1m' ;;
1281 red) echo -n $'\E[31m' ;;
1282 green) echo -n $'\E[32m' ;;
1283 blue) echo -n $'\E[34m' ;;
1284 cyan) echo -n $'\E[36m' ;;
1285 yellow) echo -n $'\E[33m' ;;
1286 purple) echo -n $'\E[35m' ;;
1287 nocolor) echo -n $'\E(B\E[m' ;;
1296 underl) echo -n $(tput smul) ;;
1297 bold) echo -n $(tput bold) ;;
1298 red) echo -n $(tput setaf 1) ;;
1299 green) echo -n $(tput setaf 2) ;;
1300 blue) echo -n $(tput setaf 4) ;;
1301 cyan) echo -n $(tput setaf 6) ;;
1302 yellow) echo -n $(tput setaf 3) ;;
1303 purple) echo -n $(tput setaf 5) ;;
1304 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1314 # Try to keep environment pollution down, EPA loves us.
1315 unset safe_term match_lhs use_color
1327 if [[ $- == *i* ]]; then
1328 # git branch/status prompt function
1329 if [[ $OS != Windows_NT ]]; then
1330 GIT_PS1_SHOWDIRTYSTATE=true
1332 # arch source lopip show -fcation
1333 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1334 # fedora/debian source
1335 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1337 # in case we didn't source git-prompt.sh
1338 if ! declare -f __git_ps1 > /dev/null; then
1344 # this needs to come before next ps1 stuff
1345 # this stuff needs bash 4, feb 2009,
1346 # old enough to no longer condition on $BASH_VERSION anymore
1350 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1352 bind -m vi-command B:shell-backward-word
1353 bind -m vi-command W:shell-forward-word
1356 if [[ $SSH_CLIENT ]]; then
1361 local return=$? # this MUST COME FIRST
1363 local ps_char ps_color
1365 history -a # save history
1366 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1367 # from the screen man page
1368 if [[ $TERM == screen* ]]; then
1369 local title_escape="\033]..2;"
1371 local title_escape="\033]0;"
1373 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1377 0) ps_color="$(get_term_color blue)"
1380 1) ps_color="$(get_term_color green)"
1381 ps_char="$return \\$"
1383 *) ps_color="$(get_term_color yellow)"
1384 ps_char="$return \\$"
1387 if [[ ! -O . ]]; then # not owner
1388 if [[ -w . ]]; then # writable
1389 ps_color="$(get_term_color bold red)"
1391 ps_color="$(get_term_color bold green)"
1394 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1395 # emacs completion doesn't like the git prompt atm, so disabling it.
1396 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1398 PROMPT_COMMAND=prompt_command
1405 ###########################################
1406 # stuff that makes sense to be at the end #
1407 ###########################################
1408 if [[ "$SUDOD" ]]; then
1411 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1420 # if someone exported $SOE, catch errors
1425 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1426 # https://github.com/rubygems/rubygems/pull/1002
1427 # further problems: installing multi-user ruby and user ruby,
1428 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1429 # There a third hybrid form, which passenger error suggested I use,
1430 # but it didn't actually work.
1432 # in cased I never need this
1433 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1434 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1435 # source $(rvm 1.9.3 do rvm env --path)
1438 # based on warning from rvmsudo
1439 export rvmsudo_secure_path=1
1441 # for other script I wrote
1442 #export ACME_TINY_PATH=/a/opt/acme-tiny
1443 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1445 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1446 source "/usr/local/rvm/scripts/rvm"
1447 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1448 source $HOME/.rvm/scripts/rvm
1452 path_add --end ~/.npm-global
1454 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1455 # i added an extra condition as gentoo xorg guide says depending on
1456 # $DISPLAY is fragile.
1457 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1460 # ensure no bad programs appending to this file will have an affect