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
207 source /a/bin/log-once/log-once-function
209 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
210 # todo, these need to be renamed to be less generic.
211 # sync overrode something else useful
212 #path_add $HOME/bin/bash-programs-by-ian/utils
219 # very few aliases, functions are always preferred.
222 if [[ $OS == Windows_NT ]]; then
223 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
225 alias j='command cygpath'
226 alias t='command cygstart'
227 alias cygstart='echo be quick, use the alias "t" instead :\)'
228 alias cygpath='echo be quick, use the alias "j" instead :\)'
233 # keep this in mind? good for safety.
238 # remove any default aliases for these
239 unalias ls ll grep &>/dev/null ||:
250 #####################
252 #####################
257 # file cut copy and paste, like the text buffers :)
258 # I havn't tested these.
259 _fbufferinit() { # internal use by
260 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
261 rm -rf "$my_f_tempdir"/*
265 cp "$@" "$my_f_tempdir"/
269 mv "$@" "$my_f_tempdir"/
271 fpst() { # file paste
272 [[ $2 ]] && { echo too many arguments; return 1; }
274 cp "$my_f_tempdir"/* "$target"
279 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
283 # join options which are continued to multiples lines onto one line
285 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
286 # remove leading spaces/tabs. assumes extglob
287 if [[ $line == "[ ]*" ]]; then
293 elif [[ $line == *=* ]]; then
294 echo "$pastline" >> "$2"
297 pastline="$pastline $line"
300 echo "$pastline" >> "$2"
306 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
307 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
309 khfix() { # known hosts fix
322 ack() { ack-grep "$@"; }
325 local startdir="$PWD"
328 ssh $x mkdir -p bin/distro-functions/src
329 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
332 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
334 tar cz * | ssh $x tar xz
339 caa() { git commit --amend --no-edit -a; }
341 calc() { echo "scale=3; $*" | bc -l; }
342 # no having to type quotes, but also no command history:
346 echo "scale=3; $x" | bc -l
353 ccat () { # config cat. see a config without extra lines.
354 grep '^\s*[^[:space:]#]' "$@"
359 # setup for format of postfix, eg:
363 local unified="$(mktemp)"
366 _cdiff-prep "$1" "$f1"
367 _cdiff-prep "$2" "$f2"
368 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
369 while IFS= read -r line; do
370 # the default bright red / blue doesn't work in emacs shell
371 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
377 if [[ $# == 0 ]]; then
378 cp /a/bin/data/COPYING .
380 cp /a/bin/data/COPYING "$@"
385 # makes it so chown -R symlink affects the symlink and its target.
386 if [[ $1 == -R ]]; then
388 command chown -h "$@"
389 command chown -R "$@"
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 --follow-symlinks -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 "$@"; }
754 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
755 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
759 pfind() { #find *$1* in $PATH
760 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
762 IFS=: pathArray=($PATH); unset IFS
763 find "${pathArray[@]}" -iname "*$1*"
767 # trash-restore lists everything that has been trashed at or below CWD
768 # This picks out files just in CWD, not subdirectories,
769 # which also match grep $1, usually use $1 for a time string
770 # which you get from running restore-trash once first
773 # last condition is to not ask again for ones we skipped
774 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
775 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
776 name="$(echo "$name" | head -n $nth | tail -n 1 )"
777 read -p "$name [Y/n] " ask
778 if [[ ! $ask || $ask == [Yy] ]]; then
779 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
780 echo $x | restore-trash > /dev/null
781 elif [[ $ask == [Nn] ]]; then
793 [[ $EUID == 0 ]] || s=s
794 $s postconf -ev "${MAPFILE[@]}"
798 rld /a/h/_site/ li:/var/www/iankelling.org/html
801 pubip() { curl -4s https://icanhazip.com; }
802 whatismyip() { pubip; }
806 apg -s -m 10 -x 14 -t
810 q() { # start / launch a program in the backround and redir output to null
815 exit "$@" 2>/dev/null
818 rbpipe() { rbt post -o --diff-filename=- "$@"; }
819 rbp() { rbt post -o "$@"; }
822 # rsync, root is required to keep permissions right.
823 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
824 # --no-times --delete
825 # basically, make an exact copy, use checksums instead of file times to be more accurate
826 rsync -ahvic --delete "$@"
829 # like rlu, but don't delete files on the target end which
830 # do not exist on the original end.
833 complete -F _rsync -o nospace rld rl rlt
836 # rl without preserving modification time.
837 rsync -ahvic --delete --no-t "$@"
840 rlu() { # [OPTS] HOST PATH
841 # eg rlu -opts frodo testpath
842 # useful for selectively sending dirs which have been synced with unison,
843 # where the path is the same on both hosts.
844 opts=("${@:1:$#-2}") # 1 to last -2
845 path="${@:$#}" # last
846 host="${@:$#-1:1}" # last -1
847 if [[ $path == .* ]]; then echo error: need absolut path; return 1; fi
848 # rync here uses checksum instead of time so we don't mess with
849 # unison relying on time as much. g is for group, same reason
850 # to keep up with unison.
851 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
855 rspicy() { # HOST DOMAIN
856 local port=$(ssh $1<<EOF
857 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
858 sed -rn "s/.*port='([0-9]+).*/\1/p"
864 echo "error: no port found. check that the domain is running."
870 # alias s='SUDOD="$PWD" sudo -i '
871 # because this is an alias, and the extra space at the end, it would allow
872 # aliases to be used with it. but aliases aren't used in scripts,
873 # better to eliminate inconsistencies. Plus, you can't do s=s; $s command
874 # with an alias, which I like to do in some functions
875 # extra space at the end allows aliases to work
877 # note: gksudo is recommended for X apps because it does not set the
878 # home directory to the same, and thus apps writing to ~ fuck things up
879 # with root owned files.
881 if [[ $EUID != 0 || $1 == -* ]]; then
882 SUDOD="$PWD" sudo -i "$@"
889 if [[ $# != 2 ]]; then
890 echo safe_rename error: $# args, need 2 >2
892 elif [[ $1 != $2 ]]; then
894 echo Cannot rename "$1" to "$2" as it already exists.
902 sb() { # sudo bash -c
903 # use sb instead of s is for sudo redirections,
904 # eg. sb 'echo "ok fine" > /etc/file'
908 complete -F _root_command s sb
912 local s; [[ $EUID != 0 ]] && s=sudo
913 if type -p systemctl &>/dev/null; then
923 if type -p systemctl &>/dev/null; then
930 # 2086 = unquoted $var
931 # 2046 = unquoted $(cmd)
932 # i had -x as an arg, but debian testing(stretch) doesn't support it
933 shellcheck -e 2086,2046,2068,2006,2119 "$@"
938 # log with script. timing is $1.t and script is $1.s
939 # -l to save to ~/typescripts/
940 # -t to add a timestamp to the filenames
941 local logdir do_stamp arg_base
942 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
945 while getopts "lt" option
948 l ) arg_base=$logdir ;;
952 shift $(($OPTIND - 1))
954 [[ -e $logdir ]] || mkdir -p $logdir
955 $do_stamp && arg_base+=$(date +%F.%T%z)
956 script -t $arg_base.s 2> $arg_base.t
958 splay() { # script replay
959 #logRoot="$HOME/typescripts/"
960 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
961 scriptreplay "$1.t" "$1.s"
965 # sudo redo. be aware, this command may not work right on strange distros or earlier software
966 if [[ $# == 0 ]]; then
967 sudo -E bash -c -l "$(history -p '!!')"
969 echo this command redos last history item. no argument is accepted
974 # with -ll, less secure but faster.
980 ssh $1 /tmp/${2##*/} "${@:2}"
986 if type -t trash-put >/dev/null; then
987 # skip args that don't exist, or else it's an err
988 for x in "$@"; do [[ ! -e $x ]] || args+=("$x"); done
989 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1000 # this goes to full width
1001 #len=${1:-$((COLUMNS -7))}
1004 if (( x == len )); then
1006 d="$(date +%l:%_M) "
1009 d=$(date +%l:%M:%_S)
1013 for ((i=0; i<x; i++)); do
1014 if (( i % 6 )); then
1032 # test existence / exists
1035 [[ -e "$x" || -L "$x" ]] || ret=1
1042 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1045 ts() { # start editing a new file
1046 [[ $# != 1 ]] && echo "I need a filename." && return 1
1048 if [[ $- != *i* ]]; then
1051 if [[ $1 == *.c ]]; then
1052 e '#include <stdio.h>' >"$1"
1053 e '#include <stdlib.h>' >>"$1"
1054 e 'int main(int argc, char * argv[]) {' >>"$1"
1055 e ' printf( "hello world\n");' >>"$1"
1056 e ' return 0;' >>"$1"
1058 e "${1%.c}: $1" > Makefile
1059 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1060 e "#!/bin/bash" >run.sh
1061 e "./${1%.c}" >>run.sh
1063 elif [[ $1 == *.java ]]; then
1064 e "public class ${1%.*} {" >"$1"
1065 e ' public static void main(String[] args) {' >>"$1"
1066 e ' System.out.println("Hello, world!");' >>"$1"
1070 echo "#!/bin/bash" > "$1"
1073 [[ $quiet ]] || g "$1"
1079 local dir="$(dirname "$1")"
1080 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1086 tx() { # toggle set -x, and the prompt so it doesn't spam
1087 if [[ $- == *x* ]]; then
1089 PROMPT_COMMAND=prompt_command
1091 unset PROMPT_COMMAND
1098 [[ $1 ]] || { e "$0: error, expected cmd to run"; return 1; }
1099 # manually run vpn so it stays within a network namespace,
1100 # until I get it all wired up with systemd.
1102 pid=$(< /run/openvpn/client.pid)
1103 if [[ ! $pid ]]; then
1104 s ip netns exec vpn /usr/sbin/openvpn --daemon ovpn --config /etc/openvpn/client.conf --cd /etc/openvpn --writepid /run/openvpn/client.pid
1105 elif [[ ! -e /proc/$pid ]]; then
1106 echo "$0: ERROR: pidfile pid $pid is not a process!!!"
1109 gksudo -- ip netns exec vpn gksudo -u ${SUDO_USER:-$USER} "$@"
1113 vc transmission-gtk&
1115 while ((i < 10)); do
1116 tun_ip=$(s ip netns exec vpn ip a show dev tun0 | sed -rn 's/^ *inet (10\.8\.\S+).*/\1/p')
1117 [[ ! $tun_ip ]] || break
1120 echo "$0: tun_ip=$tun_ip"
1121 [[ $tun_ip ]] || { e "$0: error: no tun0 addr found"; return 1; }
1122 ssh dopub bash <<EOF
1123 rule="-A PREROUTING -i eth0 -p tcp -m tcp --dport 63324 -j DNAT --to-destination $tun_ip:63324"
1125 while read -r line; do
1126 if [[ \$line == \$rule ]] && ! \$found; then
1129 iptables -t nat -D \${line#-A}
1131 done < <(iptables -t nat -S | grep -E -- '--dport\s+63324')
1132 \$found || iptables -t nat \$rule
1137 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1144 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1145 sed -r "s/listen='[^']+/listen='$ip/"> $t
1146 s virsh undefine $vm
1152 vm-set-listen $1 0.0.0.0
1157 vm-set-listen $1 127.0.0.1
1161 s systemctl start openvpn@client&
1162 journalctl --unit=openvpn@client -f -n0
1167 s systemctl stop openvpn@client
1179 # connect to vms made with virt-install
1180 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1181 sed -r "s/.*port='([0-9]+).*/\1/")
1185 whatismyip() { curl ipecho.net/plain ; echo; }
1188 #############################
1189 ######### misc stuff ########
1190 #############################
1192 if [[ $- == *i* ]]; then
1193 # commands to run when bash exits normally
1194 trap "hl; _smh" EXIT
1198 # temporary variables to test colorization
1199 # some copied from gentoo /etc/bash/bashrc,
1201 # dircolors --print-database uses its own built-in database
1202 # instead of using /etc/DIR_COLORS. Try to use the external file
1203 # first to take advantage of user additions.
1204 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1206 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1207 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1208 [[ -z ${match_lhs} ]] \
1209 && type -P dircolors >/dev/null \
1210 && match_lhs=$(dircolors --print-database)
1211 # test if our $TERM is in the TERM values in dircolor
1212 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1215 if ${use_color} && [[ $- == *i* ]]; then
1217 if [[ $XTERM_VERSION == Cygwin* ]]; then
1221 underl) echo -n $'\E[4m' ;;
1222 bold) echo -n $'\E[1m' ;;
1223 red) echo -n $'\E[31m' ;;
1224 green) echo -n $'\E[32m' ;;
1225 blue) echo -n $'\E[34m' ;;
1226 cyan) echo -n $'\E[36m' ;;
1227 yellow) echo -n $'\E[33m' ;;
1228 purple) echo -n $'\E[35m' ;;
1229 nocolor) echo -n $'\E(B\E[m' ;;
1238 underl) echo -n $(tput smul) ;;
1239 bold) echo -n $(tput bold) ;;
1240 red) echo -n $(tput setaf 1) ;;
1241 green) echo -n $(tput setaf 2) ;;
1242 blue) echo -n $(tput setaf 4) ;;
1243 cyan) echo -n $(tput setaf 6) ;;
1244 yellow) echo -n $(tput setaf 3) ;;
1245 purple) echo -n $(tput setaf 5) ;;
1246 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1256 # Try to keep environment pollution down, EPA loves us.
1257 unset safe_term match_lhs use_color
1269 if [[ $- == *i* ]]; then
1270 # git branch/status prompt function
1271 if [[ $OS != Windows_NT ]]; then
1272 GIT_PS1_SHOWDIRTYSTATE=true
1274 # arch source lopip show -fcation
1275 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1276 # fedora/debian source
1277 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1279 # in case we didn't source git-prompt.sh
1280 if ! declare -f __git_ps1 > /dev/null; then
1286 # this needs to come before next ps1 stuff
1287 # this stuff needs bash 4, feb 2009,
1288 # old enough to no longer condition on $BASH_VERSION anymore
1292 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1294 bind -m vi-command B:shell-backward-word
1295 bind -m vi-command W:shell-forward-word
1298 if [[ $SSH_CLIENT ]]; then
1303 local return=$? # this MUST COME FIRST
1305 local ps_char ps_color
1307 history -a # save history
1308 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1309 # from the screen man page
1310 if [[ $TERM == screen* ]]; then
1311 local title_escape="\033]..2;"
1313 local title_escape="\033]0;"
1315 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1319 0) ps_color="$(get_term_color blue)"
1322 1) ps_color="$(get_term_color green)"
1323 ps_char="$return \\$"
1325 *) ps_color="$(get_term_color yellow)"
1326 ps_char="$return \\$"
1329 if [[ ! -O . ]]; then # not owner
1330 if [[ -w . ]]; then # writable
1331 ps_color="$(get_term_color bold red)"
1333 ps_color="$(get_term_color bold green)"
1336 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1337 # emacs completion doesn't like the git prompt atm, so disabling it.
1338 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1340 PROMPT_COMMAND=prompt_command
1347 ###########################################
1348 # stuff that makes sense to be at the end #
1349 ###########################################
1350 if [[ "$SUDOD" ]]; then
1353 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1362 # if someone exported $SOE, catch errors
1367 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1368 # https://github.com/rubygems/rubygems/pull/1002
1369 # further problems: installing multi-user ruby and user ruby,
1370 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1371 # There a third hybrid form, which passenger error suggested I use,
1372 # but it didn't actually work.
1374 # in cased I never need this
1375 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1376 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1377 # source $(rvm 1.9.3 do rvm env --path)
1380 # based on warning from rvmsudo
1381 export rvmsudo_secure_path=1
1383 # for other script I wrote
1384 #export ACME_TINY_PATH=/a/opt/acme-tiny
1385 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1387 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1388 source "/usr/local/rvm/scripts/rvm"
1389 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1390 source $HOME/.rvm/scripts/rvm
1394 path_add --end ~/.npm-global
1396 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1397 # i added an extra condition as gentoo xorg guide says depending on
1398 # $DISPLAY is fragile.
1399 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1402 # ensure no bad programs appending to this file will have an affect