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
42 #BASH_LOGIN_SHELL=false # temporary override
44 # first conditions show that we are an ssh command without an interactive shell
45 if [[ $SSH_CONNECTION ]] \
49 && [[ ! $BASH_LOGIN_SHELL == true ]]; then
57 # note, to catch errors in functions but not outside, do:
60 # trap 'trap ERR' RETURN
72 # remove all aliases. aliases provided by the system tend to get in the way,
73 # for example, error happens if I try to define a function the same name as an alias
76 # remove gnome keyring warning messages
77 # there is probably a more proper way, but I didn't find any easily on google
78 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
79 #unset GNOME_KEYRING_CONTROL
81 # use extra globing features.
83 # include .files when globbing, but ignore files name . and ..
84 # setting this also sets dotglob.
85 # Note, this doesn't work in bash 4.4 anymore, for paths with
86 # more than 1 directory, like a/b/.foo, since * is fixed to not match /
87 export GLOBIGNORE=*/.:*/..
89 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
90 # still broken in wheezy
91 # still buggered in latest stable from the web, version 2.1
92 # perhaps its fixed in newer git version, which fails to make for me
93 # this note is from 6-2014.
94 # Also, enabling this before sourcing .bashrc makes PATH be empty.
97 # make tab on an empty line do nothing
98 shopt -s no_empty_cmd_completion
100 # advanced completion
101 # http://bash-completion.alioth.debian.org/
102 # might be sourced by the system already, but I've noticed it not being sourced before
103 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
104 . /usr/share/bash-completion/bash_completion
108 # fix spelling errors for cd, only in interactive shell
110 # append history instead of overwritting it
112 # for compatibility, per gentoo/debian bashrc
113 shopt -s checkwinsize
114 # attempt to save multiline single commands as single history entries.
121 if [[ $RLC_INSIDE_EMACS ]]; then
122 # EMACS is used by bash on startup, but we don't need it anymore.
123 # plus I hit a bug in a makefile which inherited it
125 export RLC_INSIDE_EMACS
128 # scp completion does not work, but this doesn't fix it. todo, figure this out
129 complete -r scp &> /dev/null
130 # todo, remote file completion fails, figure out how to turn it off
131 export NODE_DISABLE_COLORS=1
132 # This get's rid of ugly terminal escape chars in node repl
133 # sometime, I'd like to have completion working in emacs shell for node
134 # the offending chars can be found in lib/readline.js,
135 # things that do like:
136 # stream.write('\x1b[' + (x + 1) + 'G');
137 # We can remove them and keep readline, for example by doing this
139 #!/usr/bin/env nodejs
140 # var readline = require('readline');
141 # readline.cursorTo = function(a,b,c) {};
142 # readline.clearScreenDown = function(a) {};
143 # const repl = require('repl');
144 # var replServer = repl.start('');
146 # no prompt, or else readline complete seems to be confused, based
147 # on our column being different? node probably needs to send
148 # different kind of escape sequence that is not ugly. Anyways,
149 # completion doesn't work yet even with the ugly prompt, so whatever
151 export NODE_NO_READLINE=1
156 if [[ $- == *i* ]]; then
157 # for readline-complete.el
158 if [[ $RLC_INSIDE_EMACS ]]; then
159 # all for readline-complete.el
161 bind 'set horizontal-scroll-mode on'
162 bind 'set print-completions-horizontally on'
163 bind '"\C-i": self-insert'
165 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
166 if [[ $TERM == "xterm" ]]; then
167 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
168 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
170 bind '"\eOc": shell-forward-word'
171 bind '"\eOd": shell-backward-word'
173 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
174 # gnome-terminal, overridden by bash, or disabled by the system
175 stty werase undef lnext undef stop undef start undef
182 # history number. History expansion is good.
184 # history file size limit, set to unlimited.
185 # this needs to be different from the default because
186 # default HISTFILESIZE is 500 and could clobber our history
188 # max commands 1 session can append/read from history
190 # my own history size limit based on lines
191 HISTFILELINES=1000000
193 # the time format display when doing the history command
194 # also, setting this makes the history file record time
195 # of each command as seconds from the epoch
196 HISTTIMEFORMAT="%I:%M %p %m/%d "
197 # consecutive duplicate lines don't go in history
198 HISTCONTROL=ignoredups
199 # works in addition to HISTCONTROL to do more flexible things
200 # it could also do the same things as HISTCONTROL and thus replace it,
204 export BC_LINE_LENGTH=0
207 # note, if I use a machine I don't want files readable by all users, set
208 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
216 for _x in /a/bin/distro-functions/src/* /a/bin/!(githtml)/*-function?(s); do
220 # so I can share my bashrc
221 for x in /a/bin/bash_unpublished/source-!(.#*); do source $x; done
222 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
223 source /a/bin/log-quiet/logq-function
225 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
226 # todo, these need to be renamed to be less generic.
227 # sync overrode something else useful
228 #path_add $HOME/bin/bash-programs-by-ian/utils
236 # very few aliases, functions are always preferred.
239 if [[ $OS == Windows_NT ]]; then
240 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
242 alias j='command cygpath'
243 alias t='command cygstart'
244 alias cygstart='echo be quick, use the alias "t" instead :\)'
245 alias cygpath='echo be quick, use the alias "j" instead :\)'
250 # keep this in mind? good for safety.
255 # remove any default aliases for these
256 unalias ls ll grep &>/dev/null ||:
266 #####################
268 #####################
273 # file cut copy and paste, like the text buffers :)
274 # I havn't tested these.
275 _fbufferinit() { # internal use by
276 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
277 rm -rf "$my_f_tempdir"/*
281 cp "$@" "$my_f_tempdir"/
285 mv "$@" "$my_f_tempdir"/
287 fpst() { # file paste
288 [[ $2 ]] && { echo too many arguments; return 1; }
290 cp "$my_f_tempdir"/* "$target"
295 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
299 # join options which are continued to multiples lines onto one line
301 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
302 # remove leading spaces/tabs. assumes extglob
303 if [[ $line == "[ ]*" ]]; then
309 elif [[ $line == *=* ]]; then
310 echo "$pastline" >> "$2"
313 pastline="$pastline $line"
316 echo "$pastline" >> "$2"
321 ssh-keygen -R $h -f $(readlink -f ~/.ssh/known_hosts)
322 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
323 ssh-keygen -R $x -f $(readlink -f ~/.ssh/known_hosts)
325 khfix() { # known hosts fix
338 ack() { ack-grep "$@"; }
341 # googling android emulator libGL error: failed to load driver: r600
342 # lead to http://stackoverflow.com/a/36625175/14456
343 export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1
344 /a/opt/android-studio/bin/studio.sh "$@" &r;
348 local startdir="$PWD"
351 ssh $x mkdir -p bin/distro-functions/src
352 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
355 command cp /a/c/repos/bash/!(.git|..|.) ~/.gitconfig .
357 tar cz * | ssh $x tar xz
362 caa() { git commit --amend --no-edit -a; }
364 calc() { echo "scale=3; $*" | bc -l; }
365 # no having to type quotes, but also no command history:
369 echo "scale=3; $x" | bc -l
376 ccat () { # config cat. see a config without extra lines.
377 grep '^\s*[^[:space:]#]' "$@"
382 # setup for format of postfix, eg:
386 local unified="$(mktemp)"
389 _cdiff-prep "$1" "$f1"
390 _cdiff-prep "$2" "$f2"
391 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
392 while IFS= read -r line; do
393 # the default bright red / blue doesn't work in emacs shell
394 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
401 cp /a/bin/data/COPYING "$@"
403 cp /a/bin/data/COPYING .
409 cp /a/bin/data/LICENSE "$@"
411 cp /a/bin/data/LICENSE .
415 # makes it so chown -R symlink affects the symlink and its target.
416 if [[ $1 == -R ]]; then
418 command chown -h "$@"
419 command chown -R "$@"
430 complete -A stopped -P '"%' -S '"' d
432 dat() { # do all tee, for more complex scripts
433 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
438 for host in x2 tp treetowl; do
444 diff --strip-trailing-cr -w "$@" # diff content
447 debian_pick_mirror () {
448 # netselect-apt finds a fast mirror.
449 # but we need to replace the mirrors ourselves,
450 # because it doesn't do that. best it can do is
451 # output a basic sources file
452 # here we get the server it found, get the main server we use
453 # then substitute all instances of one for the other in the sources file
454 # and backup original to /etc/apt/sources.list-original.
455 # this is idempotent. the only way to identify debian sources is to
456 # note the original server, so we put it in a comment so we can
458 local file=$(mktemp -d)/f # safe way to get file name without creating one
459 sudo netselect-apt -o "$file" || return 1
460 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
461 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
462 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
470 safe_rename "$x" "$y"
475 date "+%A, %B %d, %r" "$@"
479 du -sh ${@:-*} | sort -h
488 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
489 emacs --eval "(ediff-files \"$1\" \"$2\")"
493 envload() { # load environment from a previous: export > file
494 local file=${1:-$HOME/.${USER}_env}
495 eval "$(export | sed 's/^declare -x/export -n/')"
496 while IFS= read -r line; do
497 # declare -x makes variables local to a function
498 eval ${line/#declare -x/export}
504 # find array. make an array of file names found by find into $x
505 # argument: find arguments
506 # return: find results in an array $x
507 while read -rd ''; do
509 done < <(find "$@" -print0);
514 if type -P firefox &>/dev/null; then
524 firefox -P alt "$@" >/dev/null 2>&1
530 local dname="${PWD##*/}"
531 local m="/a/tmp/$dname-missing"
532 local d="/a/tmp/$dname-diff"
533 [[ -e $d ]] && rm "$d"
534 [[ -e $m ]] && rm "$m"
537 while read -r line; do
539 if [[ -e "$fsfile" ]]; then
540 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
546 done < <(find -type f )
549 (( msize <= 100 )) && cat $m
553 # expected output, with different tmp dirs
554 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
555 # /a/tmp/tmp.qLDkYxBYPM-missing
564 echo different > $x/c/d
569 # test whether missing files were renamed, generally for use with fsdiff
570 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
571 # echos non-renamed files
575 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
577 while read -r line; do
578 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
580 for x in "${sums[@]}"; do
581 if [[ $missing_sum == "$x" ]]; then
586 $renamed || echo "$line"
592 command feh -FzZ "$@"
596 # like -e for functions. returns on error.
597 # at the end of the function, disable with:
599 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
600 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
607 firefox -P default "$@" >/dev/null 2>&1
611 local help="Usage: getdir [--help] PATH
612 Output the directory of PATH, or just PATH if it is a directory."
613 if [[ $1 == --help ]]; then
617 if [[ $# -ne 1 ]]; then
618 echo "getdir error: expected 1 argument, got $#"
624 local dir="$(dirname "$1")"
625 if [[ -d $dir ]]; then
628 echo "getdir error: directory does not exist"
634 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
635 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
637 gitroot || return 1 # function to set gitroot
638 builtin cd "$gitroot"
639 git symbolic-ref HEAD refs/heads/$1
645 local help="Usage: gitroot [--help]
646 Print the full path to the root of the current git repo
648 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
649 and works in older versions of git which did not have that."
650 if [[ $1 == --help ]]; then
654 local p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
655 [[ $p != /* ]] && p=$PWD
659 # quit will prompt if the program crashes.
660 gmacs() { gdb -ex=r -ex=quit --args emacs "$@"; r; }
663 git send-email --notes '--envelope-sender=<ian@iankelling.org>' \
664 --suppress-cc=self "$@"
668 grep -iIP --color=auto "$@"
672 if [[ ${#@} == 1 ]]; then
673 grep -riIP --color=auto "$@" .
675 grep -riIP --color=auto "$@"
680 # do git status on published repos
682 for x in !(forks) forks/* ian-specific/*; do
683 cd `readlink -f $x`/..
691 hl() { # history limit. Write extra history to archive file.
692 # todo: this is not working or not used currently
693 local max_lines linecount tempfile prune_lines x
694 local harchive="${HISTFILE}_archive"
695 for x in "$HISTFILE" "$harchive"; do
696 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
697 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
698 echo "error in hl: history file \$x:$x no good"
702 history -a # save history
703 max_lines=$HISTFILELINES
704 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
705 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
706 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
707 if (($linecount > $max_lines)); then
708 prune_lines=$(($linecount - $max_lines))
709 head -n $prune_lines "$HISTFILE" >> "$harchive" \
710 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
714 hr() { # horizontal row. used to break up output
715 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS)
721 # modified from ~/local/bin/git-completion.bash
722 # other completion commands are mostly taken from bash_completion package
723 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
724 || complete -o default -o nospace -F _git i
726 if ! type service &>/dev/null; then
728 echo actually running: systemctl $2 $1
741 find -L . -not \( -name .svn -prune -o -name .git -prune \
742 -o -name .hg -prune \) -iname "*$**" 2>/dev/null
746 if [[ $OS == Windows_NT ]]; then
757 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
762 if type gvfs-open &> /dev/null ; then
767 # another alternative is run-mailcap
774 grep -Il "" "$@" &>/dev/null
779 if [[ $PWD == /[iap] ]]; then
780 command ls -A --color=auto -I lost+found "$@"
782 command ls -A --color=auto "$@"
787 lcn() { locate -i "*$**"; }
789 lld() { ll -d "$@"; }
791 low() { # make filenames all lowercase
794 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
795 [[ $y != $x ]] && mv "$x" "$y"
802 lower() { # make first letter of filenames lowercase.
805 if [[ ${x::1} == [A-Z] ]]; then
806 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
807 safe_rename "$x" "$y"
813 k() { # history search
814 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40;
819 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
820 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
829 mkdir() { command mkdir -p "$@"; }
837 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
838 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
842 pfind() { #find *$1* in $PATH
843 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
845 IFS=: pathArray=($PATH); unset IFS
846 find "${pathArray[@]}" -iname "*$1*"
850 # trash-restore lists everything that has been trashed at or below CWD
851 # This picks out files just in CWD, not subdirectories,
852 # which also match grep $1, usually use $1 for a time string
853 # which you get from running restore-trash once first
856 # last condition is to not ask again for ones we skipped
857 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
858 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
859 name="$(echo "$name" | head -n $nth | tail -n 1 )"
860 read -p "$name [Y/n] " ask
861 if [[ ! $ask || $ask == [Yy] ]]; then
862 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
863 echo $x | restore-trash > /dev/null
864 elif [[ $ask == [Nn] ]]; then
876 [[ $EUID == 0 ]] || s=s
877 $s postconf -ev "${MAPFILE[@]}"
881 rld /a/h/_site/ li:/var/www/iankelling.org/html
884 pubip() { curl -4s https://icanhazip.com; }
885 whatismyip() { pubip; }
893 q() { # start / launch a program in the backround and redir output to null
898 exit "$@" 2>/dev/null
901 rbpipe() { rbt post -o --diff-filename=- "$@"; }
902 rbp() { rbt post -o "$@"; }
905 # rsync, root is required to keep permissions right.
906 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
907 # --no-times --delete
908 # basically, make an exact copy, use checksums instead of file times to be more accurate
909 rsync -ahvic --delete "$@"
912 # like rlu, but don't delete files on the target end which
913 # do not exist on the original end.
916 complete -F _rsync -o nospace rld rl rlt
919 # rl without preserving modification time.
920 rsync -ahvic --delete --no-t "$@"
923 rlu() { # [OPTS] HOST PATH
924 # eg rlu -opts frodo testpath
925 # useful for selectively sending dirs which have been synced with unison,
926 # where the path is the same on both hosts.
927 opts=("${@:1:$#-2}") # 1 to last -2
928 path="${@:$#}" # last
929 host="${@:$#-1:1}" # last -1
930 if [[ $path == .* ]]; then echo error: need absolut path; return 1; fi
931 # rync here uses checksum instead of time so we don't mess with
932 # unison relying on time as much. g is for group, same reason
933 # to keep up with unison.
934 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
938 rspicy() { # usage: HOST DOMAIN
939 # connect to spice vm remote host. use vspicy for local host
940 local port=$(ssh $1<<EOF
941 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
942 sed -rn "s/.*port='([0-9]+).*/\1/p"
948 echo "error: no port found. check that the domain is running."
954 # I use a function because otherwise we can't use in a script,
955 # can't assign to variable.
957 # note: gksudo is recommended for X apps because it does not set the
958 # home directory to the same, and thus apps writing to ~ fuck things up
959 # with root owned files.
961 if [[ $EUID != 0 || $1 == -* ]]; then
962 SUDOD="$PWD" sudo -i "$@"
969 if [[ $# != 2 ]]; then
970 echo safe_rename error: $# args, need 2 >2
972 elif [[ $1 != $2 ]]; then
974 echo Cannot rename "$1" to "$2" as it already exists.
982 sb() { # sudo bash -c
983 # use sb instead of s is for sudo redirections,
984 # eg. sb 'echo "ok fine" > /etc/file'
988 complete -F _root_command s sb
991 # s gem install scss-lint
992 pushd /a/opt/thoughtbot-guides
995 scss-lint -c /a/opt/thoughtbot-guides/style/sass/.scss-lint.yml "$@"
999 local s; [[ $EUID != 0 ]] && s=sudo
1000 if type -p systemctl &>/dev/null; then
1007 sgo() { # service go
1009 ser restart $service
1010 if type -p systemctl &>/dev/null; then
1017 # 2086 = unquoted $var
1018 # 2046 = unquoted $(cmd)
1019 # i had -x as an arg, but debian testing(stretch) doesn't support it
1020 shellcheck -e 2086,2046,2068,2006,2119 "$@"
1025 # log with script. timing is $1.t and script is $1.s
1026 # -l to save to ~/typescripts/
1027 # -t to add a timestamp to the filenames
1028 local logdir do_stamp arg_base
1029 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1032 while getopts "lt" option
1035 l ) arg_base=$logdir ;;
1036 t ) do_stamp=true ;;
1039 shift $(($OPTIND - 1))
1041 [[ -e $logdir ]] || mkdir -p $logdir
1042 $do_stamp && arg_base+=$(date +%F.%T%z)
1043 script -t $arg_base.s 2> $arg_base.t
1045 splay() { # script replay
1046 #logRoot="$HOME/typescripts/"
1047 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1048 scriptreplay "$1.t" "$1.s"
1052 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1053 if [[ $# == 0 ]]; then
1054 sudo -E bash -c -l "$(history -p '!!')"
1056 echo this command redos last history item. no argument is accepted
1061 # with -ll, less secure but faster.
1062 command srm -ll "$@"
1067 ssh $1 /tmp/${2##*/} "${@:2}"
1073 if type -t trash-put >/dev/null; then
1074 # skip args that don't exist, or else trash-put will have an error
1076 if [[ -e $x || -L $x ]]; then
1080 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1091 # this goes to full width
1092 #len=${1:-$((COLUMNS -7))}
1095 if (( x == len )); then
1097 d="$(date +%l:%_M) "
1100 d=$(date +%l:%M:%_S)
1104 for ((i=0; i<x; i++)); do
1105 if (( i % 6 )); then
1123 # test existence / exists
1126 [[ -e "$x" || -L "$x" ]] || ret=1
1133 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3 --loop=no) > /dev/null 2>&1 &
1136 ts() { # start editing a new file
1137 [[ $# != 1 ]] && echo "I need a filename." && return 1
1139 if [[ $- != *i* ]]; then
1142 if [[ $1 == *.c ]]; then
1143 e '#include <stdio.h>' >"$1"
1144 e '#include <stdlib.h>' >>"$1"
1145 e 'int main(int argc, char * argv[]) {' >>"$1"
1146 e ' printf( "hello world\n");' >>"$1"
1147 e ' return 0;' >>"$1"
1149 e "${1%.c}: $1" > Makefile
1150 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1151 e "#!/bin/bash" >run.sh
1152 e "./${1%.c}" >>run.sh
1154 elif [[ $1 == *.java ]]; then
1155 e "public class ${1%.*} {" >"$1"
1156 e ' public static void main(String[] args) {' >>"$1"
1157 e ' System.out.println("Hello, world!");' >>"$1"
1161 echo "#!/bin/bash" > "$1"
1164 [[ $quiet ]] || g "$1"
1170 local dir="$(dirname "$1")"
1171 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1177 tx() { # toggle set -x, and the prompt so it doesn't spam
1178 if [[ $- == *x* ]]; then
1180 PROMPT_COMMAND=prompt_command
1182 unset PROMPT_COMMAND
1189 [[ $1 ]] || { e "$0: error, expected cmd to run"; return 1; }
1190 # manually run vpn so it stays within a network namespace,
1191 # until I get it all wired up with systemd.
1193 pid=$(< /run/openvpn/client.pid)
1196 if [[ -e /proc/$pid ]]; then
1200 s rm -f /run/openvpn/client.pid
1203 $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
1204 gksudo -- ip netns exec vpn gksudo -u ${SUDO_USER:-$USER} "$@"
1208 vc transmission-gtk&
1212 echo "$0: error: vpn tun0 didn't show up"
1215 tun_ip=$(s ip netns exec vpn ip a show dev tun0 | sed -rn 's/^ *inet (10\.8\.\S+).*/\1/p')
1216 [[ ! $tun_ip ]] || break
1220 echo "$0: tun_ip=$tun_ip"
1221 [[ $tun_ip ]] || { e "$0: error: no tun0 addr found"; return 1; }
1222 ssh dopub bash <<EOF
1224 rule="-A PREROUTING -i eth0 -p tcp -m tcp --dport 63324 -j DNAT --to-destination $tun_ip:63324"
1226 while read -r line; do
1227 if [[ \$line == \$rule ]] && ! \$found; then
1230 iptables -t nat -D \${line#-A}
1232 done < <(iptables -t nat -S | grep -E -- '--dport\s+63324')
1233 \$found || iptables -t nat \$rule
1238 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1245 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1246 sed -r "s/listen='[^']+/listen='$ip/"> $t
1247 s virsh undefine $vm
1253 vm-set-listen $1 0.0.0.0
1258 vm-set-listen $1 127.0.0.1
1262 s systemctl start openvpn@client&
1263 journalctl --unit=openvpn@client -f -n0
1268 s systemctl stop openvpn@client
1279 vspicy() { # usage: VIRSH_DOMAIN
1280 # connect to vms made with virt-install
1281 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1282 sed -r "s/.*port='([0-9]+).*/\1/")
1286 whatismyip() { curl ipecho.net/plain ; echo; }
1289 #############################
1290 ######### misc stuff ########
1291 #############################
1293 if [[ $- == *i* ]]; then
1294 # commands to run when bash exits normally
1295 trap "hl; _smh" EXIT
1299 # temporary variables to test colorization
1300 # some copied from gentoo /etc/bash/bashrc,
1302 # dircolors --print-database uses its own built-in database
1303 # instead of using /etc/DIR_COLORS. Try to use the external file
1304 # first to take advantage of user additions.
1305 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1307 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1308 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1309 [[ -z ${match_lhs} ]] \
1310 && type -P dircolors >/dev/null \
1311 && match_lhs=$(dircolors --print-database)
1312 # test if our $TERM is in the TERM values in dircolor
1313 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1316 if ${use_color} && [[ $- == *i* ]]; then
1318 if [[ $XTERM_VERSION == Cygwin* ]]; then
1322 underl) echo -n $'\E[4m' ;;
1323 bold) echo -n $'\E[1m' ;;
1324 red) echo -n $'\E[31m' ;;
1325 green) echo -n $'\E[32m' ;;
1326 blue) echo -n $'\E[34m' ;;
1327 cyan) echo -n $'\E[36m' ;;
1328 yellow) echo -n $'\E[33m' ;;
1329 purple) echo -n $'\E[35m' ;;
1330 nocolor) echo -n $'\E(B\E[m' ;;
1339 underl) echo -n $(tput smul) ;;
1340 bold) echo -n $(tput bold) ;;
1341 red) echo -n $(tput setaf 1) ;;
1342 green) echo -n $(tput setaf 2) ;;
1343 blue) echo -n $(tput setaf 4) ;;
1344 cyan) echo -n $(tput setaf 6) ;;
1345 yellow) echo -n $(tput setaf 3) ;;
1346 purple) echo -n $(tput setaf 5) ;;
1347 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1357 # Try to keep environment pollution down, EPA loves us.
1358 unset safe_term match_lhs use_color
1370 if [[ $- == *i* ]]; then
1371 # git branch/status prompt function
1372 if [[ $OS != Windows_NT ]]; then
1373 GIT_PS1_SHOWDIRTYSTATE=true
1375 # arch source lopip show -fcation
1376 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1377 # fedora/debian source
1378 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1380 # in case we didn't source git-prompt.sh
1381 if ! declare -f __git_ps1 > /dev/null; then
1387 # this needs to come before next ps1 stuff
1388 # this stuff needs bash 4, feb 2009,
1389 # old enough to no longer condition on $BASH_VERSION anymore
1393 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1395 bind -m vi-command B:shell-backward-word
1396 bind -m vi-command W:shell-forward-word
1399 if [[ $SSH_CLIENT ]]; then
1404 local return=$? # this MUST COME FIRST
1406 local ps_char ps_color
1408 history -a # save history
1409 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1410 # from the screen man page
1411 if [[ $TERM == screen* ]]; then
1412 local title_escape="\033]..2;"
1414 local title_escape="\033]0;"
1416 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1420 0) ps_color="$(get_term_color blue)"
1423 1) ps_color="$(get_term_color green)"
1424 ps_char="$return \\$"
1426 *) ps_color="$(get_term_color yellow)"
1427 ps_char="$return \\$"
1430 if [[ ! -O . ]]; then # not owner
1431 if [[ -w . ]]; then # writable
1432 ps_color="$(get_term_color bold red)"
1434 ps_color="$(get_term_color bold green)"
1437 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1438 # emacs completion doesn't like the git prompt atm, so disabling it.
1439 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1441 PROMPT_COMMAND=prompt_command
1446 ###########################################
1447 # stuff that makes sense to be at the end #
1448 ###########################################
1449 if [[ "$SUDOD" ]]; then
1452 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1461 # if someone exported $SOE, catch errors
1466 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1467 # https://github.com/rubygems/rubygems/pull/1002
1468 # further problems: installing multi-user ruby and user ruby,
1469 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1470 # There a third hybrid form, which passenger error suggested I use,
1471 # but it didn't actually work.
1473 # in cased I never need this
1474 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1475 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1476 # source $(rvm 1.9.3 do rvm env --path)
1479 # based on warning from rvmsudo
1480 export rvmsudo_secure_path=1
1482 # for other script I wrote
1483 #export ACME_TINY_PATH=/a/opt/acme-tiny
1484 export ACME_TINY_WRAPPER_CERT_DIR=/p/c/machine_specific/$HOSTNAME/webservercerts
1486 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1487 source "/usr/local/rvm/scripts/rvm"
1488 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1489 source $HOME/.rvm/scripts/rvm
1493 path_add --end ~/.npm-global
1496 # didn't get drush working, if I did, this seems like the
1497 # only good thing to include for it.
1498 # Include Drush completion.
1499 # if [ -f "/home/ian/.drush/drush.complete.sh" ] ; then
1500 # source /home/ian/.drush/drush.complete.sh
1504 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1505 # i added an extra condition as gentoo xorg guide says depending on
1506 # $DISPLAY is fragile.
1507 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1512 # ensure no bad programs appending to this file will have an affect