3 # redirect output to log file. this doesn't work. todo figure out why
4 #exec 1>>/a/tmp/bashlog
5 #exec 2>>/a/tmp/bashlog
8 # By default this file is sourced for ALL ssh commands. This is wonky.
9 # Normally, this file is not sourced when a script is run, but we can
10 # override that by having #!/bin/bash -l. I want something similar for ssh
11 # commands. when a local script runs an ssh command, this file should not be
12 # sourced by default, but we should be able to override that.
14 # so here we test for conditions of a script under ssh and return if so. To test
15 # for an overriding condition, we have a few options. one is to use an
16 # environment variable. env variables sent across ssh are strictly limited. ssh
17 # -t which sets $SSH_TTY, but within a script that won't work because tty
18 # allocation will fail. We could override an obscure unused LC_var, like
19 # telephone, but I don't want to run into some edge case where that messes
20 # things up. we could transfer a file which we could test for, but I can't think
21 # of a way to make that inherently limited to a single ssh command. I choose to
22 # set SendEnv and AcceptEnv ssh config vars to allow the environment variable
23 # BASH_LOGIN_SHELL to propagate across ssh.
25 # assume we want ssh commands to source this file if we are sourcing it,
26 # and we haven't specified otherwise already
27 [[ ! $BASH_LOGIN_SHELL ]] && export BASH_LOGIN_SHELL=true
29 # first conditions show that we are an ssh command without an interactive shell
30 if [[ $SSH_CONNECTION ]] \
34 && [[ ! $BASH_LOGIN_SHELL == true ]]; then
42 # note, to catch errors in functions but not outside, do:
45 # trap 'trap ERR' RETURN
57 # remove all aliases. aliases provided by the system tend to get in the way,
58 # for example, error happens if I try to define a function the same name as an alias
61 # remove gnome keyring warning messages
62 # there is probably a more proper way, but I didn't find any easily on google
63 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
64 #unset GNOME_KEYRING_CONTROL
66 # use extra globing features.
68 # include .files when globbing, but ignore files name . and ..
69 # setting this also sets dotglob
70 export GLOBIGNORE=*/.:*/..
72 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
73 # still broken in wheezy
74 # still buggered in latest stable from the web, version 2.1
75 # perhaps its fixed in newer git version, which fails to make for me
76 # this note is from 6-2014.
77 # Also, enabling this before sourcing .bashrc makes PATH be empty.
80 # make tab on an empty line do nothing
81 shopt -s no_empty_cmd_completion
84 # http://bash-completion.alioth.debian.org/
85 # might be sourced by the system already, but I've noticed it not being sourced before
86 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
87 . /usr/share/bash-completion/bash_completion
91 # fix spelling errors for cd, only in interactive shell
93 # append history instead of overwritting it
95 # for compatibility, per gentoo/debian bashrc
97 # attempt to save multiline single commands as single history entries.
103 if [[ $INSIDE_EMACS ]]; then
104 # EMACS is used by bash on startup, but we don't need it anymore.
105 # plus I hit a bug in a makefile which inherited it
110 # scp completion does not work, but this doesn't fix it. todo, figure this out
111 complete -r scp &> /dev/null
112 # todo, remote file completion fails, figure out how to turn it off
113 export NODE_DISABLE_COLORS=1
114 # This get's rid of ugly terminal escape chars in node repl
115 # sometime, I'd like to have completion working in emacs shell for node
116 # the offending chars can be found in lib/readline.js,
117 # things that do like:
118 # stream.write('\x1b[' + (x + 1) + 'G');
119 # We can remove them and keep readline, for example by doing this
121 #!/usr/bin/env nodejs
122 # var readline = require('readline');
123 # readline.cursorTo = function(a,b,c) {};
124 # readline.clearScreenDown = function(a) {};
125 # const repl = require('repl');
126 # var replServer = repl.start('');
128 # no prompt, or else readline complete seems to be confused, based
129 # on our column being different? node probably needs to send
130 # different kind of escape sequence that is not ugly. Anyways,
131 # completion doesn't work yet even with the ugly prompt, so whatever
133 export NODE_NO_READLINE=1
138 if [[ $- == *i* ]]; then
139 # for readline-complete.el
140 if [[ $INSIDE_EMACS ]]; then
141 # all for readline-complete.el
143 bind 'set horizontal-scroll-mode on'
144 bind 'set print-completions-horizontally on'
145 bind '"\C-i": self-insert'
147 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
148 if [[ $TERM == "xterm" ]]; then
149 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
150 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
152 bind '"\eOc": shell-forward-word'
153 bind '"\eOd": shell-backward-word'
155 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
156 # gnome-terminal, overridden by bash, or disabled by the system
157 stty werase undef lnext undef stop undef start undef
164 # history number. History expansion is good.
166 # history file size limit, set to unlimited.
167 # this needs to be different from the default because
168 # default HISTFILESIZE is 500 and could clobber our history
170 # max commands 1 session can append/read from history
172 # my own history size limit based on lines
173 HISTFILELINES=1000000
175 # the time format display when doing the history command
176 # also, setting this makes the history file record time
177 # of each command as seconds from the epoch
178 HISTTIMEFORMAT="%I:%M %p %m/%d "
179 # consecutive duplicate lines don't go in history
180 HISTCONTROL=ignoredups
181 # works in addition to HISTCONTROL to do more flexible things
182 # it could also do the same things as HISTCONTROL and thus replace it,
186 export BC_LINE_LENGTH=0
189 # note, if I use a machine I don't want files readable by all users, set
190 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
199 for _x in /a/bin/distro-functions/src/* /a/bin/*/*-function; do
203 # so I can share my bashrc
204 for x in /a/bin/bash_unpublished/*; do source $x; done
205 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
206 source /a/bin/log-quiet/logq-function
208 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
209 # todo, these need to be renamed to be less generic.
210 # sync overrode something else useful
211 #path_add $HOME/bin/bash-programs-by-ian/utils
218 # very few aliases, functions are always preferred.
221 if [[ $OS == Windows_NT ]]; then
222 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
224 alias j='command cygpath'
225 alias t='command cygstart'
226 alias cygstart='echo be quick, use the alias "t" instead :\)'
227 alias cygpath='echo be quick, use the alias "j" instead :\)'
232 # keep this in mind? good for safety.
237 # remove any default aliases for these
238 unalias ls ll grep &>/dev/null ||:
249 #####################
251 #####################
256 # file cut copy and paste, like the text buffers :)
257 # I havn't tested these.
258 _fbufferinit() { # internal use by
259 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
260 rm -rf "$my_f_tempdir"/*
264 cp "$@" "$my_f_tempdir"/
268 mv "$@" "$my_f_tempdir"/
270 fpst() { # file paste
271 [[ $2 ]] && { echo too many arguments; return 1; }
273 cp "$my_f_tempdir"/* "$target"
278 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
282 # join options which are continued to multiples lines onto one line
284 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
285 # remove leading spaces/tabs. assumes extglob
286 if [[ $line == "[ ]*" ]]; then
292 elif [[ $line == *=* ]]; then
293 echo "$pastline" >> "$2"
296 pastline="$pastline $line"
299 echo "$pastline" >> "$2"
305 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
308 khfix() { # known hosts fix
321 ack() { ack-grep "$@"; }
324 local startdir="$PWD"
327 ssh $x mkdir -p bin/distro-functions/src
328 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
331 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
333 tar cz * | ssh $x tar xz
338 caa() { git commit --amend --no-edit -a; }
340 calc() { echo "scale=3; $*" | bc -l; }
341 # no having to type quotes, but also no command history:
345 echo "scale=3; $x" | bc -l
352 ccat () { # config cat. see a config without extra lines.
353 grep '^\s*[^[:space:]#]' "$@"
358 # setup for format of postfix, eg:
362 local unified="$(mktemp)"
365 _cdiff-prep "$1" "$f1"
366 _cdiff-prep "$2" "$f2"
367 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
368 while IFS= read -r line; do
369 # the default bright red / blue doesn't work in emacs shell
370 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
376 if [[ $# == 0 ]]; then
377 cp /a/bin/data/COPYING .
379 cp /a/bin/data/COPYING "$@"
384 # makes it so chown -R symlink affects the symlink and its target.
385 if [[ $1 == -R ]]; then
387 command chown -h "$@"
389 command chown -RH "$@"
400 complete -A stopped -P '"%' -S '"' d
402 dat() { # do all tee, for more complex scripts
403 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
408 for host in x2 tp treetowl; do
414 diff --strip-trailing-cr -w "$@" # diff content
417 debian_pick_mirror () {
418 # netselect-apt finds a fast mirror.
419 # but we need to replace the mirrors ourselves,
420 # because it doesn't do that. best it can do is
421 # output a basic sources file
422 # here we get the server it found, get the main server we use
423 # then substitute all instances of one for the other in the sources file
424 # and backup original to /etc/apt/sources.list-original.
425 # this is idempotent. the only way to identify debian sources is to
426 # note the original server, so we put it in a comment so we can
428 local file=$(mktemp -d)/f # safe way to get file name without creating one
429 sudo netselect-apt -o "$file" || return 1
430 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
431 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
432 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
440 safe_rename "$x" "$y"
445 date "+%A, %B %d, %r" "$@"
449 du -sh ${@:-*} | sort -h
458 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
459 emacs --eval "(ediff-files \"$1\" \"$2\")"
463 envload() { # load environment from a previous: export > file
464 local file=${1:-$HOME/.${USER}_env}
465 eval "$(export | sed 's/^declare -x/export -n/')"
466 while IFS= read -r line; do
467 # declare -x makes variables local to a function
468 eval ${line/#declare -x/export}
474 # find array. make an array of file names found by find into $x
475 # argument: find arguments
476 # return: find results in an array $x
477 while read -rd ''; do
479 done < <(find "$@" -print0);
484 if type -P firefox &>/dev/null; then
494 firefox -P alt "$@" >/dev/null 2>&1
500 local dname="${PWD##*/}"
501 local m="/a/tmp/$dname-missing"
502 local d="/a/tmp/$dname-diff"
503 [[ -e $d ]] && rm "$d"
504 [[ -e $m ]] && rm "$m"
507 while read -r line; do
509 if [[ -e "$fsfile" ]]; then
510 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
516 done < <(find -type f )
519 (( msize <= 100 )) && cat $m
523 # expected output, with different tmp dirs
524 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
525 # /a/tmp/tmp.qLDkYxBYPM-missing
534 echo different > $x/c/d
539 # test whether missing files were renamed, generally for use with fsdiff
540 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
541 # echos non-renamed files
545 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
547 while read -r line; do
548 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
550 for x in "${sums[@]}"; do
551 if [[ $missing_sum == "$x" ]]; then
556 $renamed || echo "$line"
563 # like -e for functions. returns on error.
564 # at the end of the function, disable with:
566 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
567 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
574 firefox -P default "$@" >/dev/null 2>&1
577 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
578 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
580 gitroot || return 1 # function to set gitroot
581 builtin cd "$gitroot"
582 git symbolic-ref HEAD refs/heads/$1
588 grep -iIP --color=auto "$@"
596 if [[ ${#@} == 1 ]]; then
597 grep -riIP --color=auto "$@" .
599 grep -riIP --color=auto "$@"
603 hl() { # history limit. Write extra history to archive file.
604 # todo: this is not working or not used currently
605 local max_lines linecount tempfile prune_lines x
606 local harchive="${HISTFILE}_archive"
607 for x in "$HISTFILE" "$harchive"; do
608 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
609 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
610 echo "error in hl: history file \$x:$x no good"
614 history -a # save history
615 max_lines=$HISTFILELINES
616 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
617 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
618 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
619 if (($linecount > $max_lines)); then
620 prune_lines=$(($linecount - $max_lines))
621 head -n $prune_lines "$HISTFILE" >> "$harchive" \
622 && sed -ie "1,${prune_lines}d" $HISTFILE
626 hr() { # horizontal row. used to break up output
627 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS)
633 # modified from ~/local/bin/git-completion.bash
634 # other completion commands are mostly taken from bash_completion package
635 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
636 || complete -o default -o nospace -F _git i
638 if ! type service &>/dev/null; then
640 echo actually running: systemctl $2 $1
653 find -L . -iname "*$**" 2>/dev/null
657 if [[ $OS == Windows_NT ]]; then
668 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
673 if type gvfs-open &> /dev/null ; then
678 # another alternative is run-mailcap
685 grep -Il "" "$@" &>/dev/null
690 if [[ $PWD == /[iap] ]]; then
691 command ls -A --color=auto -I lost+found "$@"
693 command ls -A --color=auto "$@"
698 lcn() { locate -i "*$**"; }
700 lld() { ll -d "$@"; }
702 low() { # make filenames all lowercase
705 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
706 [[ $y != $x ]] && mv "$x" "$y"
713 lower() { # make first letter of filenames lowercase.
716 if [[ ${x::1} == [A-Z] ]]; then
717 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
718 safe_rename "$x" "$y"
724 k() { # history search
725 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40;
730 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
731 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
736 [[ $(md5sum < "$1") != $(md5sum < "$2") ]]
746 mkdir() { command mkdir -p "$@"; }
749 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
750 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
754 pfind() { #find *$1* in $PATH
755 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
757 IFS=: pathArray=($PATH); unset IFS
758 find "${pathArray[@]}" -iname "*$1*"
762 # trash-restore lists everything that has been trashed at or below CWD
763 # This picks out files just in CWD, not subdirectories,
764 # which also match grep $1, usually use $1 for a time string
765 # which you get from running restore-trash once first
768 # last condition is to not ask again for ones we skipped
769 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
770 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
771 name="$(echo "$name" | head -n $nth | tail -n 1 )"
772 read -p "$name [Y/n] " ask
773 if [[ ! $ask || $ask == [Yy] ]]; then
774 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
775 echo $x | restore-trash > /dev/null
776 elif [[ $ask == [Nn] ]]; then
788 [[ $EUID == 0 ]] || s=s
789 $s postconf -ev "${MAPFILE[@]}"
793 rld /a/h/_site/ li:/var/www/iankelling.org/html
797 apg -s -m 10 -x 14 -t
801 q() { # start / launch a program in the backround and redir output to null
806 exit "$@" 2>/dev/null
809 rbpipe() { rbt post -o --diff-filename=- "$@"; }
810 rbp() { rbt post -o "$@"; }
813 # rsync, root is required to keep permissions right.
814 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
815 # --no-times --delete
816 # basically, make an exact copy, use checksums instead of file times to be more accurate
817 rsync -ahvic --delete "$@"
820 # like rlu, but don't delete files on the target end which
821 # do not exist on the original end.
824 complete -F _rsync -o nospace rld rl rlt
827 # rl without preserving modification time.
828 rsync -ahvic --delete --no-t "$@"
831 rlu() { # [OPTS] HOST PATH
832 # eg rlu -opts frodo testpath
833 # useful for selectively sending dirs which have been synced with unison,
834 # where the path is the same on both hosts.
835 opts=("${@:1:$#-2}") # 1 to last -2
836 path="${@:$#}" # last
837 host="${@:$#-1:1}" # last -1
838 # rync here uses checksum instead of time so we don't mess with
839 # unison relying on time as much. g is for group, same reason
840 # to keep up with unison.
841 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
845 rspicy() { # HOST DOMAIN
846 local port=$(ssh $1<<EOF
847 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
848 sed -rn "s/.*port='([0-9]+).*/\1/p"
854 echo "error: no port found. check that the domain is running."
860 # alias s='SUDOD="$PWD" sudo -i '
861 # because this is an alias, and the extra space at the end, it would allow
862 # aliases to be used with it. but aliases aren't used in scripts,
863 # better to eliminate inconsistencies. Plus, you can't do s=s; $s command
864 # with an alias, which I like to do in some functions
865 # extra space at the end allows aliases to work
867 # note: gksudo is recommended for X apps because it does not set the
868 # home directory to the same, and thus apps writing to ~ fuck things up
869 # with root owned files.
871 if [[ $EUID != 0 || $1 == -* ]]; then
872 SUDOD="$PWD" sudo -i "$@"
879 if [[ $# != 2 ]]; then
880 echo safe_rename error: $# args, need 2 >2
882 elif [[ $1 != $2 ]]; then
884 echo Cannot rename "$1" to "$2" as it already exists.
892 sb() { # sudo bash -c
893 # use sb instead of s is for sudo redirections,
894 # eg. sb 'echo "ok fine" > /etc/file'
898 complete -F _root_command s sb
902 local s; [[ $EUID != 0 ]] && s=sudo
903 if type -p systemctl &>/dev/null; then
913 if type -p systemctl &>/dev/null; then
920 # 2086 = unquoted $var
921 # 2046 = unquoted $(cmd)
922 # i had -x as an arg, but debian testing(stretch) doesn't support it
923 shellcheck -e 2086,2046,2068,2006,2119 "$@"
928 # log with script. timing is $1.t and script is $1.s
929 # -l to save to ~/typescripts/
930 # -t to add a timestamp to the filenames
931 local logdir do_stamp arg_base
932 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
935 while getopts "lt" option
938 l ) arg_base=$logdir ;;
942 shift $(($OPTIND - 1))
944 [[ -e $logdir ]] || mkdir -p $logdir
945 $do_stamp && arg_base+=$(date +%F.%T%z)
946 script -t $arg_base.s 2> $arg_base.t
948 splay() { # script replay
949 #logRoot="$HOME/typescripts/"
950 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
951 scriptreplay "$1.t" "$1.s"
955 # sudo redo. be aware, this command may not work right on strange distros or earlier software
956 if [[ $# == 0 ]]; then
957 sudo -E bash -c -l "$(history -p '!!')"
959 echo this command redos last history item. no argument is accepted
964 # with -ll, less secure but faster.
971 if type -t trash-put >/dev/null; then
972 # skip args that don't exist, or else it's an err
973 for x in "$@"; do [[ ! -e $x ]] || args+=("$x"); done
974 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
985 # this goes to full width
986 #len=${1:-$((COLUMNS -7))}
989 if (( x == len )); then
998 for ((i=0; i<x; i++)); do
1017 # test existence / exists
1020 [[ -e "$x" || -L "$x" ]] || ret=1
1027 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1030 ts() { # start editing a new file
1031 [[ $# != 1 ]] && echo "I need a filename." && return 1
1033 if [[ $- != *i* ]]; then
1036 if [[ $1 == *.c ]]; then
1037 e '#include <stdio.h>' >"$1"
1038 e '#include <stdlib.h>' >>"$1"
1039 e 'int main(int argc, char * argv[]) {' >>"$1"
1040 e ' printf( "hello world\n");' >>"$1"
1041 e ' return 0;' >>"$1"
1043 e "${1%.c}: $1" > Makefile
1044 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1045 e "#!/bin/bash" >run.sh
1046 e "./${1%.c}" >>run.sh
1048 elif [[ $1 == *.java ]]; then
1049 e "public class ${1%.*} {" >"$1"
1050 e ' public static void main(String[] args) {' >>"$1"
1051 e ' System.out.println("Hello, world!");' >>"$1"
1055 echo "#!/bin/bash" > "$1"
1058 [[ $quiet ]] || g "$1"
1064 local dir="$(dirname "$1")"
1065 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1071 tx() { # toggle set -x, and the prompt so it doesn't spam
1072 if [[ $- == *x* ]]; then
1074 PROMPT_COMMAND=prompt_command
1076 unset PROMPT_COMMAND
1083 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1090 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1091 sed -r "s/listen='[^']+/listen='$ip/"> $t
1092 s virsh undefine $vm
1098 vm-set-listen $1 0.0.0.0
1103 vm-set-listen $1 127.0.0.1
1107 s systemctl start openvpn@client&
1108 journalctl --unit=openvpn@client -f -n0
1112 s systemctl stop openvpn@client
1124 # connect to vms made with virt-install
1125 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1126 sed -r "s/.*port='([0-9]+).*/\1/")
1130 whatismyip() { curl ipecho.net/plain ; echo; }
1133 #############################
1134 ######### misc stuff ########
1135 #############################
1137 if [[ $- == *i* ]]; then
1138 # commands to run when bash exits normally
1139 trap "hl; _smh" EXIT
1143 # temporary variables to test colorization
1144 # some copied from gentoo /etc/bash/bashrc,
1146 # dircolors --print-database uses its own built-in database
1147 # instead of using /etc/DIR_COLORS. Try to use the external file
1148 # first to take advantage of user additions.
1149 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1151 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1152 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1153 [[ -z ${match_lhs} ]] \
1154 && type -P dircolors >/dev/null \
1155 && match_lhs=$(dircolors --print-database)
1156 # test if our $TERM is in the TERM values in dircolor
1157 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1160 if ${use_color} && [[ $- == *i* ]]; then
1162 if [[ $XTERM_VERSION == Cygwin* ]]; then
1166 underl) echo -n $'\E[4m' ;;
1167 bold) echo -n $'\E[1m' ;;
1168 red) echo -n $'\E[31m' ;;
1169 green) echo -n $'\E[32m' ;;
1170 blue) echo -n $'\E[34m' ;;
1171 cyan) echo -n $'\E[36m' ;;
1172 yellow) echo -n $'\E[33m' ;;
1173 purple) echo -n $'\E[35m' ;;
1174 nocolor) echo -n $'\E(B\E[m' ;;
1183 underl) echo -n $(tput smul) ;;
1184 bold) echo -n $(tput bold) ;;
1185 red) echo -n $(tput setaf 1) ;;
1186 green) echo -n $(tput setaf 2) ;;
1187 blue) echo -n $(tput setaf 4) ;;
1188 cyan) echo -n $(tput setaf 6) ;;
1189 yellow) echo -n $(tput setaf 3) ;;
1190 purple) echo -n $(tput setaf 5) ;;
1191 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1201 # Try to keep environment pollution down, EPA loves us.
1202 unset safe_term match_lhs use_color
1214 if [[ $- == *i* ]]; then
1215 # git branch/status prompt function
1216 if [[ $OS != Windows_NT ]]; then
1217 GIT_PS1_SHOWDIRTYSTATE=true
1219 # arch source lopip show -fcation
1220 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1221 # fedora/debian source
1222 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1224 # in case we didn't source git-prompt.sh
1225 if ! declare -f __git_ps1 > /dev/null; then
1231 # this needs to come before next ps1 stuff
1232 # this stuff needs bash 4, feb 2009,
1233 # old enough to no longer condition on $BASH_VERSION anymore
1237 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1239 bind -m vi-command B:shell-backward-word
1240 bind -m vi-command W:shell-forward-word
1243 if [[ $SSH_CLIENT ]]; then
1248 local return=$? # this MUST COME FIRST
1250 local ps_char ps_color
1252 history -a # save history
1253 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1254 # from the screen man page
1255 if [[ $TERM == screen* ]]; then
1256 local title_escape="\033]..2;"
1258 local title_escape="\033]0;"
1260 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1264 0) ps_color="$(get_term_color blue)"
1267 1) ps_color="$(get_term_color green)"
1268 ps_char="$return \\$"
1270 *) ps_color="$(get_term_color yellow)"
1271 ps_char="$return \\$"
1274 if [[ ! -O . ]]; then # not owner
1275 if [[ -w . ]]; then # writable
1276 ps_color="$(get_term_color bold red)"
1278 ps_color="$(get_term_color bold green)"
1281 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1282 # emacs completion doesn't like the git prompt atm, so disabling it.
1283 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1285 PROMPT_COMMAND=prompt_command
1292 ###########################################
1293 # stuff that makes sense to be at the end #
1294 ###########################################
1295 if [[ "$SUDOD" ]]; then
1298 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1307 # if someone exported $SOE, catch errors
1312 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1313 # https://github.com/rubygems/rubygems/pull/1002
1314 # further problems: installing multi-user ruby and user ruby,
1315 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1316 # There a third hybrid form, which passenger error suggested I use,
1317 # but it didn't actually work.
1319 # in cased I never need this
1320 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1321 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1322 # source $(rvm 1.9.3 do rvm env --path)
1325 # based on warning from rvmsudo
1326 export rvmsudo_secure_path=1
1328 # for other script I wrote
1329 export ACME_TINY_PATH=/a/opt/acme-tiny
1330 export lt ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME
1332 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1333 source "/usr/local/rvm/scripts/rvm"
1334 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1335 source $HOME/.rvm/scripts/rvm
1338 mkdir -p ~/.npm-global
1339 npm config set prefix '~/.npm-global'
1340 path_add --end ~/.npm-global
1342 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1343 # i added an extra condition as gentoo xorg guide says depending on
1344 # $DISPLAY is fragile.
1345 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1348 # ensure no bad programs appending to this file will have an affect