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/*/*-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
221 source /a/bin/log-quiet/log-once-function
223 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
224 # todo, these need to be renamed to be less generic.
225 # sync overrode something else useful
226 #path_add $HOME/bin/bash-programs-by-ian/utils
233 # very few aliases, functions are always preferred.
236 if [[ $OS == Windows_NT ]]; then
237 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
239 alias j='command cygpath'
240 alias t='command cygstart'
241 alias cygstart='echo be quick, use the alias "t" instead :\)'
242 alias cygpath='echo be quick, use the alias "j" instead :\)'
247 # keep this in mind? good for safety.
252 # remove any default aliases for these
253 unalias ls ll grep &>/dev/null ||:
264 #####################
266 #####################
271 # file cut copy and paste, like the text buffers :)
272 # I havn't tested these.
273 _fbufferinit() { # internal use by
274 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
275 rm -rf "$my_f_tempdir"/*
279 cp "$@" "$my_f_tempdir"/
283 mv "$@" "$my_f_tempdir"/
285 fpst() { # file paste
286 [[ $2 ]] && { echo too many arguments; return 1; }
288 cp "$my_f_tempdir"/* "$target"
293 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
297 # join options which are continued to multiples lines onto one line
299 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
300 # remove leading spaces/tabs. assumes extglob
301 if [[ $line == "[ ]*" ]]; then
307 elif [[ $line == *=* ]]; then
308 echo "$pastline" >> "$2"
311 pastline="$pastline $line"
314 echo "$pastline" >> "$2"
319 ssh-keygen -R $h -f $(readlink -f ~/.ssh/known_hosts)
320 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
321 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
323 khfix() { # known hosts fix
336 ack() { ack-grep "$@"; }
339 local startdir="$PWD"
342 ssh $x mkdir -p bin/distro-functions/src
343 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
346 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
348 tar cz * | ssh $x tar xz
353 caa() { git commit --amend --no-edit -a; }
355 calc() { echo "scale=3; $*" | bc -l; }
356 # no having to type quotes, but also no command history:
360 echo "scale=3; $x" | bc -l
367 ccat () { # config cat. see a config without extra lines.
368 grep '^\s*[^[:space:]#]' "$@"
373 # setup for format of postfix, eg:
377 local unified="$(mktemp)"
380 _cdiff-prep "$1" "$f1"
381 _cdiff-prep "$2" "$f2"
382 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
383 while IFS= read -r line; do
384 # the default bright red / blue doesn't work in emacs shell
385 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
392 cp /a/bin/data/COPYING "$@"
394 cp /a/bin/data/COPYING .
400 cp /a/bin/data/LICENSE "$@"
402 cp /a/bin/data/LICENSE .
406 # makes it so chown -R symlink affects the symlink and its target.
407 if [[ $1 == -R ]]; then
409 command chown -h "$@"
410 command chown -R "$@"
421 complete -A stopped -P '"%' -S '"' d
423 dat() { # do all tee, for more complex scripts
424 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
429 for host in x2 tp treetowl; do
435 diff --strip-trailing-cr -w "$@" # diff content
438 debian_pick_mirror () {
439 # netselect-apt finds a fast mirror.
440 # but we need to replace the mirrors ourselves,
441 # because it doesn't do that. best it can do is
442 # output a basic sources file
443 # here we get the server it found, get the main server we use
444 # then substitute all instances of one for the other in the sources file
445 # and backup original to /etc/apt/sources.list-original.
446 # this is idempotent. the only way to identify debian sources is to
447 # note the original server, so we put it in a comment so we can
449 local file=$(mktemp -d)/f # safe way to get file name without creating one
450 sudo netselect-apt -o "$file" || return 1
451 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
452 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
453 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
461 safe_rename "$x" "$y"
466 date "+%A, %B %d, %r" "$@"
470 du -sh ${@:-*} | sort -h
479 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
480 emacs --eval "(ediff-files \"$1\" \"$2\")"
484 envload() { # load environment from a previous: export > file
485 local file=${1:-$HOME/.${USER}_env}
486 eval "$(export | sed 's/^declare -x/export -n/')"
487 while IFS= read -r line; do
488 # declare -x makes variables local to a function
489 eval ${line/#declare -x/export}
495 # find array. make an array of file names found by find into $x
496 # argument: find arguments
497 # return: find results in an array $x
498 while read -rd ''; do
500 done < <(find "$@" -print0);
505 if type -P firefox &>/dev/null; then
515 firefox -P alt "$@" >/dev/null 2>&1
521 local dname="${PWD##*/}"
522 local m="/a/tmp/$dname-missing"
523 local d="/a/tmp/$dname-diff"
524 [[ -e $d ]] && rm "$d"
525 [[ -e $m ]] && rm "$m"
528 while read -r line; do
530 if [[ -e "$fsfile" ]]; then
531 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
537 done < <(find -type f )
540 (( msize <= 100 )) && cat $m
544 # expected output, with different tmp dirs
545 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
546 # /a/tmp/tmp.qLDkYxBYPM-missing
555 echo different > $x/c/d
560 # test whether missing files were renamed, generally for use with fsdiff
561 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
562 # echos non-renamed files
566 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
568 while read -r line; do
569 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
571 for x in "${sums[@]}"; do
572 if [[ $missing_sum == "$x" ]]; then
577 $renamed || echo "$line"
584 # like -e for functions. returns on error.
585 # at the end of the function, disable with:
587 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
588 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
595 firefox -P default "$@" >/dev/null 2>&1
599 local help="Usage: getdir [--help] PATH
600 Output the directory of PATH, or just PATH if it is a directory."
601 if [[ $1 == --help ]]; then
605 if [[ $# -ne 1 ]]; then
606 echo "getdir error: expected 1 argument, got $#"
612 local dir="$(dirname "$1")"
613 if [[ -d $dir ]]; then
616 echo "getdir error: directory does not exist"
622 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
623 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
625 gitroot || return 1 # function to set gitroot
626 builtin cd "$gitroot"
627 git symbolic-ref HEAD refs/heads/$1
633 grep -iIP --color=auto "$@"
641 if [[ ${#@} == 1 ]]; then
642 grep -riIP --color=auto "$@" .
644 grep -riIP --color=auto "$@"
648 hl() { # history limit. Write extra history to archive file.
649 # todo: this is not working or not used currently
650 local max_lines linecount tempfile prune_lines x
651 local harchive="${HISTFILE}_archive"
652 for x in "$HISTFILE" "$harchive"; do
653 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
654 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
655 echo "error in hl: history file \$x:$x no good"
659 history -a # save history
660 max_lines=$HISTFILELINES
661 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
662 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
663 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
664 if (($linecount > $max_lines)); then
665 prune_lines=$(($linecount - $max_lines))
666 head -n $prune_lines "$HISTFILE" >> "$harchive" \
667 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
671 hr() { # horizontal row. used to break up output
672 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS)
678 # modified from ~/local/bin/git-completion.bash
679 # other completion commands are mostly taken from bash_completion package
680 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
681 || complete -o default -o nospace -F _git i
683 if ! type service &>/dev/null; then
685 echo actually running: systemctl $2 $1
698 find -L . -iname "*$**" 2>/dev/null
702 if [[ $OS == Windows_NT ]]; then
713 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
718 if type gvfs-open &> /dev/null ; then
723 # another alternative is run-mailcap
730 grep -Il "" "$@" &>/dev/null
735 if [[ $PWD == /[iap] ]]; then
736 command ls -A --color=auto -I lost+found "$@"
738 command ls -A --color=auto "$@"
743 lcn() { locate -i "*$**"; }
745 lld() { ll -d "$@"; }
747 low() { # make filenames all lowercase
750 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
751 [[ $y != $x ]] && mv "$x" "$y"
758 lower() { # make first letter of filenames lowercase.
761 if [[ ${x::1} == [A-Z] ]]; then
762 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
763 safe_rename "$x" "$y"
769 k() { # history search
770 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40;
775 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
776 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
785 mkdir() { command mkdir -p "$@"; }
793 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
794 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
798 pfind() { #find *$1* in $PATH
799 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
801 IFS=: pathArray=($PATH); unset IFS
802 find "${pathArray[@]}" -iname "*$1*"
806 # trash-restore lists everything that has been trashed at or below CWD
807 # This picks out files just in CWD, not subdirectories,
808 # which also match grep $1, usually use $1 for a time string
809 # which you get from running restore-trash once first
812 # last condition is to not ask again for ones we skipped
813 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
814 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
815 name="$(echo "$name" | head -n $nth | tail -n 1 )"
816 read -p "$name [Y/n] " ask
817 if [[ ! $ask || $ask == [Yy] ]]; then
818 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
819 echo $x | restore-trash > /dev/null
820 elif [[ $ask == [Nn] ]]; then
832 [[ $EUID == 0 ]] || s=s
833 $s postconf -ev "${MAPFILE[@]}"
837 rld /a/h/_site/ li:/var/www/iankelling.org/html
840 pubip() { curl -4s https://icanhazip.com; }
841 whatismyip() { pubip; }
845 apg -s -m 10 -x 14 -t
849 q() { # start / launch a program in the backround and redir output to null
854 exit "$@" 2>/dev/null
857 rbpipe() { rbt post -o --diff-filename=- "$@"; }
858 rbp() { rbt post -o "$@"; }
861 # rsync, root is required to keep permissions right.
862 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
863 # --no-times --delete
864 # basically, make an exact copy, use checksums instead of file times to be more accurate
865 rsync -ahvic --delete "$@"
868 # like rlu, but don't delete files on the target end which
869 # do not exist on the original end.
872 complete -F _rsync -o nospace rld rl rlt
875 # rl without preserving modification time.
876 rsync -ahvic --delete --no-t "$@"
879 rlu() { # [OPTS] HOST PATH
880 # eg rlu -opts frodo testpath
881 # useful for selectively sending dirs which have been synced with unison,
882 # where the path is the same on both hosts.
883 opts=("${@:1:$#-2}") # 1 to last -2
884 path="${@:$#}" # last
885 host="${@:$#-1:1}" # last -1
886 if [[ $path == .* ]]; then echo error: need absolut path; return 1; fi
887 # rync here uses checksum instead of time so we don't mess with
888 # unison relying on time as much. g is for group, same reason
889 # to keep up with unison.
890 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
894 rspicy() { # HOST DOMAIN
895 local port=$(ssh $1<<EOF
896 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
897 sed -rn "s/.*port='([0-9]+).*/\1/p"
903 echo "error: no port found. check that the domain is running."
909 # I use a function because otherwise we can't use in a script,
910 # can't assign to variable.
912 # note: gksudo is recommended for X apps because it does not set the
913 # home directory to the same, and thus apps writing to ~ fuck things up
914 # with root owned files.
916 if [[ $EUID != 0 || $1 == -* ]]; then
917 SUDOD="$PWD" sudo -i "$@"
924 if [[ $# != 2 ]]; then
925 echo safe_rename error: $# args, need 2 >2
927 elif [[ $1 != $2 ]]; then
929 echo Cannot rename "$1" to "$2" as it already exists.
937 sb() { # sudo bash -c
938 # use sb instead of s is for sudo redirections,
939 # eg. sb 'echo "ok fine" > /etc/file'
943 complete -F _root_command s sb
947 local s; [[ $EUID != 0 ]] && s=sudo
948 if type -p systemctl &>/dev/null; then
958 if type -p systemctl &>/dev/null; then
965 # 2086 = unquoted $var
966 # 2046 = unquoted $(cmd)
967 # i had -x as an arg, but debian testing(stretch) doesn't support it
968 shellcheck -e 2086,2046,2068,2006,2119 "$@"
973 # log with script. timing is $1.t and script is $1.s
974 # -l to save to ~/typescripts/
975 # -t to add a timestamp to the filenames
976 local logdir do_stamp arg_base
977 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
980 while getopts "lt" option
983 l ) arg_base=$logdir ;;
987 shift $(($OPTIND - 1))
989 [[ -e $logdir ]] || mkdir -p $logdir
990 $do_stamp && arg_base+=$(date +%F.%T%z)
991 script -t $arg_base.s 2> $arg_base.t
993 splay() { # script replay
994 #logRoot="$HOME/typescripts/"
995 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
996 scriptreplay "$1.t" "$1.s"
1000 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1001 if [[ $# == 0 ]]; then
1002 sudo -E bash -c -l "$(history -p '!!')"
1004 echo this command redos last history item. no argument is accepted
1009 # with -ll, less secure but faster.
1010 command srm -ll "$@"
1015 ssh $1 /tmp/${2##*/} "${@:2}"
1021 if type -t trash-put >/dev/null; then
1022 # skip args that don't exist, or else it's an err
1023 for x in "$@"; do [[ ! -e $x ]] || args+=("$x"); done
1024 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1035 # this goes to full width
1036 #len=${1:-$((COLUMNS -7))}
1039 if (( x == len )); then
1041 d="$(date +%l:%_M) "
1044 d=$(date +%l:%M:%_S)
1048 for ((i=0; i<x; i++)); do
1049 if (( i % 6 )); then
1067 # test existence / exists
1070 [[ -e "$x" || -L "$x" ]] || ret=1
1077 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1080 ts() { # start editing a new file
1081 [[ $# != 1 ]] && echo "I need a filename." && return 1
1083 if [[ $- != *i* ]]; then
1086 if [[ $1 == *.c ]]; then
1087 e '#include <stdio.h>' >"$1"
1088 e '#include <stdlib.h>' >>"$1"
1089 e 'int main(int argc, char * argv[]) {' >>"$1"
1090 e ' printf( "hello world\n");' >>"$1"
1091 e ' return 0;' >>"$1"
1093 e "${1%.c}: $1" > Makefile
1094 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1095 e "#!/bin/bash" >run.sh
1096 e "./${1%.c}" >>run.sh
1098 elif [[ $1 == *.java ]]; then
1099 e "public class ${1%.*} {" >"$1"
1100 e ' public static void main(String[] args) {' >>"$1"
1101 e ' System.out.println("Hello, world!");' >>"$1"
1105 echo "#!/bin/bash" > "$1"
1108 [[ $quiet ]] || g "$1"
1114 local dir="$(dirname "$1")"
1115 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1121 tx() { # toggle set -x, and the prompt so it doesn't spam
1122 if [[ $- == *x* ]]; then
1124 PROMPT_COMMAND=prompt_command
1126 unset PROMPT_COMMAND
1133 [[ $1 ]] || { e "$0: error, expected cmd to run"; return 1; }
1134 # manually run vpn so it stays within a network namespace,
1135 # until I get it all wired up with systemd.
1137 pid=$(< /run/openvpn/client.pid)
1138 if [[ ! $pid ]]; then
1139 s ip netns exec vpn /usr/sbin/openvpn --daemon ovpn --config /etc/openvpn/client.conf --cd /etc/openvpn --writepid /run/openvpn/client.pid
1140 elif [[ ! -e /proc/$pid ]]; then
1141 echo "$0: ERROR: pidfile pid $pid is not a process!!!"
1144 gksudo -- ip netns exec vpn gksudo -u ${SUDO_USER:-$USER} "$@"
1148 vc transmission-gtk&
1150 while ((i < 10)); do
1151 tun_ip=$(s ip netns exec vpn ip a show dev tun0 | sed -rn 's/^ *inet (10\.8\.\S+).*/\1/p')
1152 [[ ! $tun_ip ]] || break
1155 echo "$0: tun_ip=$tun_ip"
1156 [[ $tun_ip ]] || { e "$0: error: no tun0 addr found"; return 1; }
1157 ssh dopub bash <<EOF
1158 rule="-A PREROUTING -i eth0 -p tcp -m tcp --dport 63324 -j DNAT --to-destination $tun_ip:63324"
1160 while read -r line; do
1161 if [[ \$line == \$rule ]] && ! \$found; then
1164 iptables -t nat -D \${line#-A}
1166 done < <(iptables -t nat -S | grep -E -- '--dport\s+63324')
1167 \$found || iptables -t nat \$rule
1172 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1179 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1180 sed -r "s/listen='[^']+/listen='$ip/"> $t
1181 s virsh undefine $vm
1187 vm-set-listen $1 0.0.0.0
1192 vm-set-listen $1 127.0.0.1
1196 s systemctl start openvpn@client&
1197 journalctl --unit=openvpn@client -f -n0
1202 s systemctl stop openvpn@client
1214 # connect to vms made with virt-install
1215 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1216 sed -r "s/.*port='([0-9]+).*/\1/")
1220 whatismyip() { curl ipecho.net/plain ; echo; }
1223 #############################
1224 ######### misc stuff ########
1225 #############################
1227 if [[ $- == *i* ]]; then
1228 # commands to run when bash exits normally
1229 trap "hl; _smh" EXIT
1233 # temporary variables to test colorization
1234 # some copied from gentoo /etc/bash/bashrc,
1236 # dircolors --print-database uses its own built-in database
1237 # instead of using /etc/DIR_COLORS. Try to use the external file
1238 # first to take advantage of user additions.
1239 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1241 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1242 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1243 [[ -z ${match_lhs} ]] \
1244 && type -P dircolors >/dev/null \
1245 && match_lhs=$(dircolors --print-database)
1246 # test if our $TERM is in the TERM values in dircolor
1247 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1250 if ${use_color} && [[ $- == *i* ]]; then
1252 if [[ $XTERM_VERSION == Cygwin* ]]; then
1256 underl) echo -n $'\E[4m' ;;
1257 bold) echo -n $'\E[1m' ;;
1258 red) echo -n $'\E[31m' ;;
1259 green) echo -n $'\E[32m' ;;
1260 blue) echo -n $'\E[34m' ;;
1261 cyan) echo -n $'\E[36m' ;;
1262 yellow) echo -n $'\E[33m' ;;
1263 purple) echo -n $'\E[35m' ;;
1264 nocolor) echo -n $'\E(B\E[m' ;;
1273 underl) echo -n $(tput smul) ;;
1274 bold) echo -n $(tput bold) ;;
1275 red) echo -n $(tput setaf 1) ;;
1276 green) echo -n $(tput setaf 2) ;;
1277 blue) echo -n $(tput setaf 4) ;;
1278 cyan) echo -n $(tput setaf 6) ;;
1279 yellow) echo -n $(tput setaf 3) ;;
1280 purple) echo -n $(tput setaf 5) ;;
1281 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1291 # Try to keep environment pollution down, EPA loves us.
1292 unset safe_term match_lhs use_color
1304 if [[ $- == *i* ]]; then
1305 # git branch/status prompt function
1306 if [[ $OS != Windows_NT ]]; then
1307 GIT_PS1_SHOWDIRTYSTATE=true
1309 # arch source lopip show -fcation
1310 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1311 # fedora/debian source
1312 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1314 # in case we didn't source git-prompt.sh
1315 if ! declare -f __git_ps1 > /dev/null; then
1321 # this needs to come before next ps1 stuff
1322 # this stuff needs bash 4, feb 2009,
1323 # old enough to no longer condition on $BASH_VERSION anymore
1327 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1329 bind -m vi-command B:shell-backward-word
1330 bind -m vi-command W:shell-forward-word
1333 if [[ $SSH_CLIENT ]]; then
1338 local return=$? # this MUST COME FIRST
1340 local ps_char ps_color
1342 history -a # save history
1343 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1344 # from the screen man page
1345 if [[ $TERM == screen* ]]; then
1346 local title_escape="\033]..2;"
1348 local title_escape="\033]0;"
1350 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1354 0) ps_color="$(get_term_color blue)"
1357 1) ps_color="$(get_term_color green)"
1358 ps_char="$return \\$"
1360 *) ps_color="$(get_term_color yellow)"
1361 ps_char="$return \\$"
1364 if [[ ! -O . ]]; then # not owner
1365 if [[ -w . ]]; then # writable
1366 ps_color="$(get_term_color bold red)"
1368 ps_color="$(get_term_color bold green)"
1371 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1372 # emacs completion doesn't like the git prompt atm, so disabling it.
1373 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1375 PROMPT_COMMAND=prompt_command
1382 ###########################################
1383 # stuff that makes sense to be at the end #
1384 ###########################################
1385 if [[ "$SUDOD" ]]; then
1388 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1397 # if someone exported $SOE, catch errors
1402 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1403 # https://github.com/rubygems/rubygems/pull/1002
1404 # further problems: installing multi-user ruby and user ruby,
1405 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1406 # There a third hybrid form, which passenger error suggested I use,
1407 # but it didn't actually work.
1409 # in cased I never need this
1410 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1411 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1412 # source $(rvm 1.9.3 do rvm env --path)
1415 # based on warning from rvmsudo
1416 export rvmsudo_secure_path=1
1418 # for other script I wrote
1419 #export ACME_TINY_PATH=/a/opt/acme-tiny
1420 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1422 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1423 source "/usr/local/rvm/scripts/rvm"
1424 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1425 source $HOME/.rvm/scripts/rvm
1429 path_add --end ~/.npm-global
1431 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1432 # i added an extra condition as gentoo xorg guide says depending on
1433 # $DISPLAY is fragile.
1434 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1437 # ensure no bad programs appending to this file will have an affect