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
116 if [[ $- == *i* ]]; then
117 # for readline-complete.el
118 if [[ $INSIDE_EMACS ]]; then
119 # all for readline-complete.el
121 bind 'set horizontal-scroll-mode on'
122 bind 'set print-completions-horizontally on'
123 bind '"\C-i": self-insert'
125 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
126 if [[ $TERM == "xterm" ]]; then
127 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
128 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
130 bind '"\eOc": shell-forward-word'
131 bind '"\eOd": shell-backward-word'
133 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
134 # gnome-terminal, overridden by bash, or disabled by the system
135 stty werase undef lnext undef stop undef start undef
142 # history number. History expansion is good.
144 # history file size limit, set to unlimited.
145 # this needs to be different from the default because
146 # default HISTFILESIZE is 500 and could clobber our history
148 # max commands 1 session can append/read from history
150 # my own history size limit based on lines
151 HISTFILELINES=1000000
153 # the time format display when doing the history command
154 # also, setting this makes the history file record time
155 # of each command as seconds from the epoch
156 HISTTIMEFORMAT="%I:%M %p %m/%d "
157 # consecutive duplicate lines don't go in history
158 HISTCONTROL=ignoredups
159 # works in addition to HISTCONTROL to do more flexible things
160 # it could also do the same things as HISTCONTROL and thus replace it,
164 export BC_LINE_LENGTH=0
167 # note, if I use a machine I don't want files readable by all users, set
168 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
177 for _x in /a/bin/distro-functions/src/* /a/bin/*/*-function; do
181 # so I can share my bashrc
182 for x in /a/bin/bash_unpublished/*; do source $x; done
183 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
184 source /a/bin/log-quiet/logq-function
186 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
187 # todo, these need to be renamed to be less generic.
188 # sync overrode something else useful
189 #path_add $HOME/bin/bash-programs-by-ian/utils
196 # very few aliases, functions are always preferred.
199 if [[ $OS == Windows_NT ]]; then
200 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
202 alias j='command cygpath'
203 alias t='command cygstart'
204 alias cygstart='echo be quick, use the alias "t" instead :\)'
205 alias cygpath='echo be quick, use the alias "j" instead :\)'
210 # keep this in mind? good for safety.
215 # remove any default aliases for these
216 unalias ls ll grep &>/dev/null ||:
227 #####################
229 #####################
232 mkdir() { command mkdir -p "$@"; }
241 # file cut copy and paste, like the text buffers :)
242 # I havn't tested these.
243 _fbufferinit() { # internal use by
244 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
245 rm -rf "$my_f_tempdir"/*
249 cp "$@" "$my_f_tempdir"/
253 mv "$@" "$my_f_tempdir"/
255 fpst() { # file paste
256 [[ $2 ]] && { echo too many arguments; return 1; }
258 cp "$my_f_tempdir"/* "$target"
262 k() { grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 40; }
264 # horizontal row. used to break up output
265 hr() { printf "$(tput setaf 5)█$(tput sgr0)%.0s" $(seq $COLUMNS); }
270 find -L . -iname "*$**" 2>/dev/null
273 # test existence / exists
277 [[ -e "$x" || -L "$x" ]] || ret=1
283 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
285 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
290 complete -F _root_command s sb
294 # join options which are continued to multiples lines onto one line
296 grep -vE '^([ \t]*#|^[ \t]*$)' "$1" | while IFS= read -r line; do
297 # remove leading spaces/tabs. assumes extglob
298 if [[ $line == "[ ]*" ]]; then
304 elif [[ $line == *=* ]]; then
305 echo "$pastline" >> "$2"
308 pastline="$pastline $line"
311 echo "$pastline" >> "$2"
317 local x=$(timeout 0.1 ssh -v $1 |& sed -rn "s/debug1: Connecting to $h \[([^\]*)].*/\1/p");
320 khfix() { # known hosts fix
333 ack() { ack-grep "$@"; }
336 local startdir="$PWD"
339 ssh $x mkdir -p bin/distro-functions/src
340 tar cz bin/semi-private bin/distro-functions/src | ssh $x tar xz
343 command cp /a/c/repos/bash/!(.git) ~/.gitconfig .
345 tar cz * | ssh $x tar xz
350 caa() { git commit --amend --no-edit -a; }
352 calc() { echo "scale=3; $*" | bc -l; }
353 # no having to type quotes, but also no command history:
357 echo "scale=3; $x" | bc -l
364 ccat () { # config cat. see a config without extra lines.
365 grep '^\s*[^[:space:]#]' "$@"
370 # setup for format of postfix, eg:
374 local unified="$(mktemp)"
377 _cdiff-prep "$1" "$f1"
378 _cdiff-prep "$2" "$f2"
379 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
380 while IFS= read -r line; do
381 # the default bright red / blue doesn't work in emacs shell
382 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
388 if [[ $# == 0 ]]; then
389 cp /a/bin/data/COPYING .
391 cp /a/bin/data/COPYING "$@"
396 # makes it so chown -R symlink affects the symlink and its target.
397 if [[ $1 == -R ]]; then
399 command chown -h "$@"
401 command chown -RH "$@"
412 complete -A stopped -P '"%' -S '"' d
414 dat() { # do all tee, for more complex scripts
415 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
420 for host in x2 tp treetowl; do
426 diff --strip-trailing-cr -w "$@" # diff content
429 debian_pick_mirror () {
430 # netselect-apt finds a fast mirror.
431 # but we need to replace the mirrors ourselves,
432 # because it doesn't do that. best it can do is
433 # output a basic sources file
434 # here we get the server it found, get the main server we use
435 # then substitute all instances of one for the other in the sources file
436 # and backup original to /etc/apt/sources.list-original.
437 # this is idempotent. the only way to identify debian sources is to
438 # note the original server, so we put it in a comment so we can
440 local file=$(mktemp -d)/f # safe way to get file name without creating one
441 sudo netselect-apt -o "$file" || return 1
442 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
443 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
444 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
452 safe_rename "$x" "$y"
457 date "+%A, %B %d, %r" "$@"
461 du -sh ${@:-*} | sort -h
470 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
471 emacs --eval "(ediff-files \"$1\" \"$2\")"
475 envload() { # load environment from a previous: export > file
476 local file=${1:-$HOME/.${USER}_env}
477 eval "$(export | sed 's/^declare -x/export -n/')"
478 while IFS= read -r line; do
479 # declare -x makes variables local to a function
480 eval ${line/#declare -x/export}
486 # find array. make an array of file names found by find into $x
487 # argument: find arguments
488 # return: find results in an array $x
489 while read -rd ''; do
491 done < <(find "$@" -print0);
496 if type -P firefox &>/dev/null; then
506 firefox -P alt "$@" >/dev/null 2>&1
512 local dname="${PWD##*/}"
513 local m="/a/tmp/$dname-missing"
514 local d="/a/tmp/$dname-diff"
515 [[ -e $d ]] && rm "$d"
516 [[ -e $m ]] && rm "$m"
519 while read -r line; do
521 if [[ -e "$fsfile" ]]; then
522 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
528 done < <(find -type f )
531 (( msize <= 100 )) && cat $m
535 # expected output, with different tmp dirs
536 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
537 # /a/tmp/tmp.qLDkYxBYPM-missing
546 echo different > $x/c/d
551 # test whether missing files were renamed, generally for use with fsdiff
552 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
553 # echos non-renamed files
557 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
559 while read -r line; do
560 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
562 for x in "${sums[@]}"; do
563 if [[ $missing_sum == "$x" ]]; then
568 $renamed || echo "$line"
575 # like -e for functions. returns on error.
576 # at the end of the function, disable with:
578 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
579 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
586 firefox -P default "$@" >/dev/null 2>&1
589 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
590 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
592 gitroot || return 1 # function to set gitroot
593 builtin cd "$gitroot"
594 git symbolic-ref HEAD refs/heads/$1
600 grep -iIP --color=auto "$@"
608 if [[ ${#@} == 1 ]]; then
609 grep -riIP --color=auto "$@" .
611 grep -riIP --color=auto "$@"
616 hl() { # history limit. Write extra history to archive file.
617 # todo: this is not working or not used currently
618 local max_lines linecount tempfile prune_lines x
619 local harchive="${HISTFILE}_archive"
620 for x in "$HISTFILE" "$harchive"; do
621 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
622 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
623 echo "error in hl: history file \$x:$x no good"
627 history -a # save history
628 max_lines=$HISTFILELINES
629 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
630 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
631 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
632 if (($linecount > $max_lines)); then
633 prune_lines=$(($linecount - $max_lines))
634 head -n $prune_lines "$HISTFILE" >> "$harchive" \
635 && sed -ie "1,${prune_lines}d" $HISTFILE
640 # modified from ~/local/bin/git-completion.bash
641 # other completion commands are mostly taken from bash_completion package
642 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
643 || complete -o default -o nospace -F _git i
645 if ! type service &>/dev/null; then
647 echo actually running: systemctl $2 $1
655 if [[ $OS == Windows_NT ]]; then
666 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
671 if type gvfs-open &> /dev/null ; then
676 # another alternative is run-mailcap
683 grep -Il "" "$@" &>/dev/null
688 if [[ $PWD == /[iap] ]]; then
689 command ls -A --color=auto -I lost+found "$@"
691 command ls -A --color=auto "$@"
696 lcn() { locate -i "*$**"; }
698 lld() { ll -d "$@"; }
700 low() { # make filenames all lowercase
703 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
704 [[ $y != $x ]] && mv "$x" "$y"
711 lower() { # make first letter of filenames lowercase.
714 if [[ ${x::1} == [A-Z] ]]; then
715 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
716 safe_rename "$x" "$y"
722 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
723 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
728 [[ $(md5sum < "$1") != $(md5sum < "$2") ]]
740 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
741 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
745 pfind() { #find *$1* in $PATH
746 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
748 IFS=: pathArray=($PATH); unset IFS
749 find "${pathArray[@]}" -iname "*$1*"
753 # trash-restore lists everything that has been trashed at or below CWD
754 # This picks out files just in CWD, not subdirectories,
755 # which also match grep $1, usually use $1 for a time string
756 # which you get from running restore-trash once first
759 # last condition is to not ask again for ones we skipped
760 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
761 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
762 name="$(echo "$name" | head -n $nth | tail -n 1 )"
763 read -p "$name [Y/n] " ask
764 if [[ ! $ask || $ask == [Yy] ]]; then
765 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
766 echo $x | restore-trash > /dev/null
767 elif [[ $ask == [Nn] ]]; then
779 [[ $EUID == 0 ]] || s=s
780 $s postconf -ev "${MAPFILE[@]}"
784 rld /a/h/_site/ li:/var/www/iankelling.org/html
788 apg -s -m 10 -x 14 -t
792 q() { # start / launch a program in the backround and redir output to null
797 exit "$@" 2>/dev/null
800 rbpipe() { rbt post -o --diff-filename=- "$@"; }
801 rbp() { rbt post -o "$@"; }
804 # rsync, root is required to keep permissions right.
805 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
806 # --no-times --delete
807 # basically, make an exact copy, use checksums instead of file times to be more accurate
808 rsync -ahvic --delete "$@"
811 # like rlu, but don't delete files on the target end which
812 # do not exist on the original end.
815 complete -F _rsync -o nospace rld rl rlt
818 # rl without preserving modification time.
819 rsync -ahvic --delete --no-t "$@"
822 rlu() { # [OPTS] HOST PATH
823 # eg rlu -opts frodo testpath
824 # useful for selectively sending dirs which have been synced with unison,
825 # where the path is the same on both hosts.
826 opts=("${@:1:$#-2}") # 1 to last -2
827 path="${@:$#}" # last
828 host="${@:$#-1:1}" # last -1
829 # rync here uses checksum instead of time so we don't mess with
830 # unison relying on time as much. g is for group, same reason
831 # to keep up with unison.
832 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
836 rspicy() { # HOST DOMAIN
837 local port=$(ssh $1<<EOF
838 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
839 sed -rn "s/.*port='([0-9]+).*/\1/p"
845 echo "error: no port found. check that the domain is running."
851 # alias s='SUDOD="$PWD" sudo -i '
852 # because this is an alias, and the extra space at the end, it would allow
853 # aliases to be used with it. but aliases aren't used in scripts,
854 # better to eliminate inconsistencies. Plus, you can't do s=s; $s command
855 # with an alias, which I like to do in some functions
856 # extra space at the end allows aliases to work
858 # note: gksudo is recommended for X apps because it does not set the
859 # home directory to the same, and thus apps writing to ~ fuck things up
860 # with root owned files.
862 if [[ $EUID != 0 || $1 == -* ]]; then
863 SUDOD="$PWD" sudo -i "$@"
870 if [[ $# != 2 ]]; then
871 echo safe_rename error: $# args, need 2 >2
873 elif [[ $1 != $2 ]]; then
875 echo Cannot rename "$1" to "$2" as it already exists.
887 local s; [[ $EUID != 0 ]] && s=sudo
888 if type -p systemctl &>/dev/null; then
898 if type -p systemctl &>/dev/null; then
905 # 2086 = unquoted $var
906 # 2046 = unquoted $(cmd)
907 # i had -x as an arg, but debian testing(stretch) doesn't support it
908 shellcheck -e 2086,2046,2068,2006,2119 "$@"
913 # log with script. timing is $1.t and script is $1.s
914 # -l to save to ~/typescripts/
915 # -t to add a timestamp to the filenames
916 local logdir do_stamp arg_base
917 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
920 while getopts "lt" option
923 l ) arg_base=$logdir ;;
927 shift $(($OPTIND - 1))
929 [[ -e $logdir ]] || mkdir -p $logdir
930 $do_stamp && arg_base+=$(date +%F.%T%z)
931 script -t $arg_base.s 2> $arg_base.t
933 splay() { # script replay
934 #logRoot="$HOME/typescripts/"
935 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
936 scriptreplay "$1.t" "$1.s"
940 # sudo redo. be aware, this command may not work right on strange distros or earlier software
941 if [[ $# == 0 ]]; then
942 sudo -E bash -c -l "$(history -p '!!')"
944 echo this command redos last history item. no argument is accepted
949 # with -ll, less secure but faster.
956 if type -t trash-put >/dev/null; then
957 # skip args that don't exist, or else it's an err
958 for x in "$@"; do [[ ! -e $x ]] || args+=("$x"); done
959 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
970 # this goes to full width
971 #len=${1:-$((COLUMNS -7))}
974 if (( x == len )); then
983 for ((i=0; i<x; i++)); do
1003 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1006 ts() { # start editing a new file
1007 [[ $# != 1 ]] && echo "I need a filename." && return 1
1009 if [[ $- != *i* ]]; then
1012 if [[ $1 == *.c ]]; then
1013 e '#include <stdio.h>' >"$1"
1014 e '#include <stdlib.h>' >>"$1"
1015 e 'int main(int argc, char * argv[]) {' >>"$1"
1016 e ' printf( "hello world\n");' >>"$1"
1017 e ' return 0;' >>"$1"
1019 e "${1%.c}: $1" > Makefile
1020 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
1021 e "#!/bin/bash" >run.sh
1022 e "./${1%.c}" >>run.sh
1024 elif [[ $1 == *.java ]]; then
1025 e "public class ${1%.*} {" >"$1"
1026 e ' public static void main(String[] args) {' >>"$1"
1027 e ' System.out.println("Hello, world!");' >>"$1"
1031 echo "#!/bin/bash" > "$1"
1034 [[ $quiet ]] || g "$1"
1040 local dir="$(dirname "$1")"
1041 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1047 tx() { # toggle set -x, and the prompt so it doesn't spam
1048 if [[ $- == *x* ]]; then
1050 PROMPT_COMMAND=prompt_command
1052 unset PROMPT_COMMAND
1059 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1066 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1067 sed -r "s/listen='[^']+/listen='$ip/"> $t
1068 s virsh undefine $vm
1074 vm-set-listen $1 0.0.0.0
1079 vm-set-listen $1 127.0.0.1
1083 s systemctl start openvpn@client&
1084 journalctl --unit=openvpn@client -f -n0
1088 s systemctl stop openvpn@client
1100 # connect to vms made with virt-install
1101 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1102 sed -r "s/.*port='([0-9]+).*/\1/")
1106 whatismyip() { curl ipecho.net/plain ; echo; }
1109 #############################
1110 ######### misc stuff ########
1111 #############################
1113 if [[ $- == *i* ]]; then
1114 # commands to run when bash exits normally
1115 trap "hl; _smh" EXIT
1119 # temporary variables to test colorization
1120 # some copied from gentoo /etc/bash/bashrc,
1122 # dircolors --print-database uses its own built-in database
1123 # instead of using /etc/DIR_COLORS. Try to use the external file
1124 # first to take advantage of user additions.
1125 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1127 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1128 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1129 [[ -z ${match_lhs} ]] \
1130 && type -P dircolors >/dev/null \
1131 && match_lhs=$(dircolors --print-database)
1132 # test if our $TERM is in the TERM values in dircolor
1133 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1136 if ${use_color} && [[ $- == *i* ]]; then
1138 if [[ $XTERM_VERSION == Cygwin* ]]; then
1142 underl) echo -n $'\E[4m' ;;
1143 bold) echo -n $'\E[1m' ;;
1144 red) echo -n $'\E[31m' ;;
1145 green) echo -n $'\E[32m' ;;
1146 blue) echo -n $'\E[34m' ;;
1147 cyan) echo -n $'\E[36m' ;;
1148 yellow) echo -n $'\E[33m' ;;
1149 purple) echo -n $'\E[35m' ;;
1150 nocolor) echo -n $'\E(B\E[m' ;;
1159 underl) echo -n $(tput smul) ;;
1160 bold) echo -n $(tput bold) ;;
1161 red) echo -n $(tput setaf 1) ;;
1162 green) echo -n $(tput setaf 2) ;;
1163 blue) echo -n $(tput setaf 4) ;;
1164 cyan) echo -n $(tput setaf 6) ;;
1165 yellow) echo -n $(tput setaf 3) ;;
1166 purple) echo -n $(tput setaf 5) ;;
1167 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1177 # Try to keep environment pollution down, EPA loves us.
1178 unset safe_term match_lhs use_color
1190 if [[ $- == *i* ]]; then
1191 # git branch/status prompt function
1192 if [[ $OS != Windows_NT ]]; then
1193 GIT_PS1_SHOWDIRTYSTATE=true
1195 # arch source lopip show -fcation
1196 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1197 # fedora/debian source
1198 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1200 # in case we didn't source git-prompt.sh
1201 if ! declare -f __git_ps1 > /dev/null; then
1207 # this needs to come before next ps1 stuff
1208 # this stuff needs bash 4, feb 2009,
1209 # old enough to no longer condition on $BASH_VERSION anymore
1213 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
1215 bind -m vi-command B:shell-backward-word
1216 bind -m vi-command W:shell-forward-word
1219 if [[ $SSH_CLIENT ]]; then
1224 local return=$? # this MUST COME FIRST
1226 local ps_char ps_color
1228 history -a # save history
1229 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
1230 # from the screen man page
1231 if [[ $TERM == screen* ]]; then
1232 local title_escape="\033]..2;"
1234 local title_escape="\033]0;"
1236 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
1240 0) ps_color="$(get_term_color blue)"
1243 1) ps_color="$(get_term_color green)"
1244 ps_char="$return \\$"
1246 *) ps_color="$(get_term_color yellow)"
1247 ps_char="$return \\$"
1250 if [[ ! -O . ]]; then # not owner
1251 if [[ -w . ]]; then # writable
1252 ps_color="$(get_term_color bold red)"
1254 ps_color="$(get_term_color bold green)"
1257 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1258 # emacs completion doesn't like the git prompt atm, so disabling it.
1259 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1261 PROMPT_COMMAND=prompt_command
1268 ###########################################
1269 # stuff that makes sense to be at the end #
1270 ###########################################
1271 if [[ "$SUDOD" ]]; then
1274 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1283 # if someone exported $SOE, catch errors
1288 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1289 # https://github.com/rubygems/rubygems/pull/1002
1290 # further problems: installing multi-user ruby and user ruby,
1291 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1292 # There a third hybrid form, which passenger error suggested I use,
1293 # but it didn't actually work.
1295 # in cased I never need this
1296 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1297 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
1298 # source $(rvm 1.9.3 do rvm env --path)
1301 # based on warning from rvmsudo
1302 export rvmsudo_secure_path=1
1305 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
1306 source "/usr/local/rvm/scripts/rvm"
1307 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
1308 source $HOME/.rvm/scripts/rvm
1311 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
1312 # i added an extra condition as gentoo xorg guide says depending on
1313 # $DISPLAY is fragile.
1314 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
1317 # ensure no bad programs appending to this file will have an affect