various updates
[distro-setup] / .bashrc
1 # to debug
2 #set -x
3 # redirect output to log file
4 #exec 1>/a/tmp/bashlog
5 #exec 2>/a/tmp/bashlog
6
7
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, and it would be much
10 # better and more consistent if that also happened when when running a script
11 # over ssh. so here we test for conditions of a script under ssh and return if
12 # so. we can override with ssh -t which sets $SSH_TTY, which we can detect
13 # But inside a script, ssh -t won't work, because we aren't using a tty at all.
14 # So we need something else. Command lines and env variables sent across ssh are strictly limited.
15 # We could override an obscure unused LC_var, like telephone, or we could transfer a file.
16 # But I choose to set SendEnv and AcceptEnv ssh vars for BASH_LOGIN_SHELL.
17 # In a private file, i have aliases for if $- == *i*, ssh -t, else ssh.
18
19 [[ $- != *i* && ! $SSH_CONNECTION ]] && export BASH_LOGIN_SHELL=true
20
21 if [[ $SSH_CONNECTION ]] \
22 && [[ $- == *c* ]] \
23 && [[ ! $SSH_TTY ]] \
24 && [[ ! $BASH_LOGIN_SHELL == true ]] \
25 && [[ $- != *i* ]]; then
26 return
27 fi
28
29 # Side note on ssh.
30
31
32
33 ###################
34 ## include files ###
35 ###################
36
37 for x in $HOME/bin/bash-programs-by-ian/repos/*/*-function; do
38 source "$x"
39 done
40
41 source $HOME/bin/semi-private # so I can share my bashrc
42 source $HOME/path_add-function
43
44
45
46
47 ############
48 # settings #
49 ############
50
51 CDPATH=.:/a
52
53 # remove gnome keyring warning messages
54 # there is probably a more proper way, but I didn't find any easily on google
55 unset GNOME_KEYRING_CONTROL
56
57 #use extra globing features. See man bash, search extglob.
58 shopt -s extglob
59 #include .files when globbing.
60 shopt -s dotglob
61 #but ignore files name . and ..
62 #those are default when this is set to anything, so we just set it to one of them
63 export GLOBIGNORE=.
64
65 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
66 # still broken in wheezy
67 # still buggered in latest stable from the web, version 2.1
68 # perhaps its fixed in newer git version, which fails to make for me
69 # this note is from 6-2014
70 #shopt -s nullglob
71
72 # make tab on an empty line do nothing
73 shopt -s no_empty_cmd_completion
74
75 # advanced completion
76 # http://bash-completion.alioth.debian.org/
77 # might be sourced by the system already, but I've noticed it not being sourced before
78 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
79 . /usr/share/bash-completion/bash_completion
80 fi
81
82
83 # fix spelling errors for cd, only in interactive shell
84 shopt -s cdspell
85 # append history instead of overwritting it
86 shopt -s histappend
87 # for compatibility, per gentoo/debian bashrc
88 shopt -s checkwinsize
89 # attempt to save multiline single commands as single history entries.
90 shopt -s cmdhist
91 shopt -s globstar
92
93
94 # inside emacs fixes
95 if [[ $INSIDE_EMACS ]]; then
96 export INSIDE_EMACS
97 export PAGER=cat
98 export MANPAGER=cat
99 # for readline-complete.el
100 stty echo
101 fi
102
103
104 if [[ $- == *i* ]]; then
105 # for readline-complete.el
106 if [[ $INSIDE_EMACS ]]; then
107 bind 'set horizontal-scroll-mode on'
108 bind 'set print-completions-horizontally on'
109 bind '"\C-i": self-insert'
110 else
111 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
112 if [[ $TERM == "xterm" ]]; then
113 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
114 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
115 else
116 bind '"\eOc": shell-forward-word'
117 bind '"\eOd": shell-backward-word'
118 fi
119 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
120 # gnome-terminal, overridden by bash, or disabled by the system
121 stty werase undef lnext undef stop undef start undef
122
123 fi
124
125 fi
126
127
128 # history number. History expansion is good.
129 PS4='$LINENO+ '
130 # history file size limit, set to unlimited.
131 # this needs to be different from the default because
132 # default HISTFILESIZE is 500 and could clobber our history
133 HISTFILESIZE=
134 # max commands 1 session can append/read from history
135 HISTSIZE=100000
136 # my own history size limit based on lines
137 HISTFILELINES=1000000
138 HISTFILE=$HOME/.bh
139 # the time format display when doing the history command
140 # also, setting this makes the history file record time
141 # of each command as seconds from the epoch
142 HISTTIMEFORMAT="%I:%M %p %m/%d "
143 # consecutive duplicate lines don't go in history
144 HISTCONTROL=ignoredups
145 # just defensively unsetting this
146 # this var can replace HISTCONTROL to do more flexible things like
147 # not saving single char history items or specific names
148 unset HISTIGNORE
149
150 export BC_LINE_LENGTH=0
151
152 path_add --ifexists /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
153 path_add $HOME/bin/bash-programs-by-ian/utils
154 # note, if I use a machine I don't want files readable by all users, set
155 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
156
157 C_DEFAULT_DIR=/a
158
159
160
161
162 ###############
163 ### aliases ###
164 ###############
165
166 if [[ $- == *i* ]]; then
167 alias cp='cp -i'
168 alias mv='mv -i'
169 fi
170
171 # remove any default aliases for these
172 alias ls > /dev/null 2>&1 && unalias ls
173 alias ll > /dev/null 2>&1 && unalias ll
174 alias grep > /dev/null 2>&1 && unalias grep
175
176
177 mkdir() {
178 command mkdir -p "$@"
179 }
180
181
182 alias d='builtin bg'
183 complete -A stopped -P '"%' -S '"' d
184
185 alias hi='history'
186
187
188 # note: gksudo is recommended for X apps because it does not set the
189 # home directory to the same.
190
191 if [[ $- == *i* ]]; then
192 # extra space at the end allows aliases to work
193 alias s='SUDOD="$PWD" sudo -i '
194 else
195 s() {
196 if [[ $EUID != 0 || $1 == -* ]]; then
197 local SUDOD="$PWD"
198 sudo -i "$@"
199 else
200 "$@"
201 fi
202 }
203 fi
204
205
206
207 if [[ $OS == Windows_NT ]]; then
208 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
209 export DISPLAY=nt
210 alias j='command cygpath'
211 alias t='command cygstart'
212 alias cygstart='echo be quick, use the alias "t" instead :\)'
213 alias cygpath='echo be quick, use the alias "j" instead :\)'
214
215 fi
216
217
218 #####################
219 ### functions ####
220 #####################
221
222 # netselect-apt finds a fast mirror.
223 # but we need to replace the mirrors ourselves,
224 # because it doesn't do that. best it can do is
225 # output a basic sources file
226 # here we get the server it found, get the main server we use
227 # then substitute all instances of one for the other in the sources file
228 # and backup original to /etc/apt/sources.list-original.
229 # this is idempotent
230 debian_pick_mirror () {
231 local x=$(mktemp -d)/f # safe way to get file name without creating one
232 sudo netselect-apt -o $x || return 1
233 x=$(_debian_pick_mirror_grep stable $x)
234 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
235 sudo sed -i "s/$(_debian_pick_mirror_grep wheezy)/$x/" /etc/apt/sources.list
236 }
237
238 _debian_pick_mirror_grep () {
239 local x="$(grep -oP "^deb [^ ]+ $1 " ${2-/etc/apt/sources.list})"
240 x="${x#deb }"
241 x="${x% $1 }"
242 # replace / with \/ so we can use it with sed
243 echo "${x//\//\\/}"
244 }
245
246 a() {
247 beet "${@}"
248 }
249
250
251 t() {
252 trash-put "$@"
253 }
254
255
256 if type ack-grep >/dev/null 2>&1; then
257 alias ack=ack-grep
258 fi
259
260
261 gr() {
262 grep -i --binary-files=without-match --color=auto "$@"
263 }
264
265 grr() {
266 grep -ri --binary-files=without-match --color=auto "$@"
267 }
268
269
270
271
272 calc() { echo "scale=3; $*" | bc -l; }
273
274
275 # makes it so chown -R symlink affects the symlink and its target.
276 chown() {
277 if [[ $1 == -R ]]; then
278 shift
279 command chown -h "$@"
280 command chown "$@"
281 command chown -RH "$@"
282 else
283 command chown "$@"
284 fi
285 }
286
287
288
289 cgpl ()
290 {
291 if [[ $# == 0 ]]; then
292 cp /a/bin/data/COPYING .
293 else
294 cp /a/bin/data/COPYING "$@"
295 fi
296 }
297
298
299 dc() {
300 diff --strip-trailing-cr -w "$@" # diff content
301 }
302
303
304 distro_name() {
305 if [[ -f /etc/fedora-release ]]; then
306 echo fedora
307 else
308 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
309 fi
310 }
311
312
313 dt() {
314 date "+%A, %B %d, %r" "$@"
315 }
316
317
318 e() { echo "$@"; }
319
320
321 envload() { # load environment from a previous: export > file
322 local file=${1:-$HOME/.${USER}_env}
323 eval "$(export | sed 's/^declare -x/export -n/')"
324 while IFS= read -r line; do
325 # declare -x makes variables local to a function
326 eval ${line/#declare -x/export}
327 done < "$file"
328 }
329
330
331
332 # havn't tested these:
333 #file cut copy and paste, like the text buffers :)
334 _fbufferinit() { # internal use by
335 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
336 rm -rf "$my_f_tempdir"/*
337 }
338 fcp() { # file cp
339 _fbufferinit
340 cp "$@" "$my_f_tempdir"/
341 }
342 fct() { # file cut
343 _fbufferinit
344 mv "$@" "$my_f_tempdir"/
345 }
346 fpst() { # file paste
347 [[ $2 ]] && { echo too many arguments; return 1; }
348 target=${1:-.}
349 cp "$my_f_tempdir"/* "$target"
350 }
351
352
353 # find array. make an array of file names found by find into $x
354 # argument: find arguments
355 # return: find results in an array $x
356 fa() {
357 while read -rd ''; do
358 x+=("$REPLY");
359 done < <(find "$@" -print0);
360 }
361
362
363 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
364 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
365 local gitroot
366 gitroot || return 1 # function to set gitroot
367 builtin cd $gitroot
368 git symbolic-ref HEAD refs/heads/$1
369 rm .git/index
370 git clean -fdx
371 }
372
373 fw() {
374 firefox -P default "$@" >/dev/null 2>&1
375 }
376
377 fn() {
378 firefox -P alt "$@" >/dev/null 2>&1
379 }
380
381
382
383
384
385 # horizontal row. used to break up output
386 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
387
388
389 i() {
390 git "$@"
391 }
392 # modified from ~/local/bin/git-completion.bash
393 # other completion commands are mostly taken from bash_completion package
394 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
395 || complete -o default -o nospace -F _git i
396
397 # fast commit
398 ic() {
399 git commit -am "$*"
400 }
401
402 # insensitive find
403 ifn () {
404 find . -iname '*'"$*"'*'
405 }
406
407
408
409
410 l() {
411 if [[ $PWD == /[iap] ]]; then
412 command ls -A --color=auto -I lost+found "$@"
413 else
414 command ls -A --color=auto "$@"
415 fi
416 }
417
418
419 lld() { ll -d "$@"; }
420
421
422 low() { # make filenames all lowercase
423 local x y
424 for x in "$@"; do
425 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
426 [[ $y != $x ]] && mv "$x" "$y"
427 done
428 }
429
430
431 lower() { # make first letter of filenames lowercase.
432 local x
433 for x in "$@"; do
434 if [[ ${x::1} == [A-Z] ]]; then
435 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
436 safe_rename "$x" "$y"
437 fi
438 done
439 }
440
441 safe_rename() {
442 if [[ $# != 2 ]]; then
443 echo safe_rename error: $# args, need 2 >2
444 return 1
445 elif [[ $1 != $2 ]]; then
446 if [[ -e $2 ]]; then
447 echo Cannot rename "$1" to "$2" as it already exists.
448 else
449 mv "$1" "$2"
450 fi
451 fi
452 }
453
454 despace() {
455 local x y
456 for x in "$@"; do
457 y="${x// /_}"
458 safe_rename "$x" "$y"
459 done
460 }
461
462
463 # package manager
464 # aliases would be much more compact, but they can't be used as ssh commands
465 # also, to be used in a script, you need -i which prints annoying
466 # warnings. instead, use -l in a script to source this file
467 if type -p yum > /dev/null; then
468 p() {
469 if [[ $EUID == 0 ]]; then
470 yum "$@"
471 else
472 sudo yum "$@"
473 fi
474 }
475 pi() {
476 if [[ $EUID == 0 ]]; then
477 yum -y install "$@"
478 else
479 sudo yum -y install "$@"
480 fi
481 }
482 pf() {
483 if [[ $EUID == 0 ]]; then
484 yum search "$@"
485 else
486 sudo yum search "$@"
487 fi
488 }
489 else
490 p() {
491 if [[ $EUID == 0 ]]; then
492 aptitude "$@"
493 else
494 sudo aptitude "$@"
495 fi
496 }
497 pi() {
498 if [[ $EUID == 0 ]]; then
499 aptitude -y install "$@"
500 else
501 sudo aptitude -y install "$@"
502 fi
503 }
504 pf() {
505 # scratch a very annoying itch.
506 # package description width as wide as the screen, and package name field small
507 # aptitude manual can't figure out how wide emacs terminal is,
508 # of course it doesn't consult the $COLUMNS variable...
509 # and in a normal terminal, it makes the package name field ridiculously big
510 # also, remove that useless dash before the description
511 if [[ $EUID == 0 ]]; then
512 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
513 else
514 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
515 fi
516 }
517 fi
518
519
520 # test existence / exists
521 te() {
522 local ret=0
523 for x in "$@"; do
524 [[ -e "$x" || -L "$x" ]] || ret=1
525 done
526 return $ret
527 }
528
529
530 # fix root file ownership for FILE argument.
531 # check if parent or grandparent is not root and if the dir of FILE is also
532 # owned by that user, and change ownership to that user
533 perm_fix() {
534 local parent
535 if [[ $EUID == 0 ]]; then
536 te "$1" || touch $1
537 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
538 argdir=$(getdir "$1")
539 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
540 if ! chown "--reference=$argdir" "$1"; then
541 echo failed to fix bad ownership file permissons
542 return 1
543 fi
544 fi
545 fi
546 fi
547 }
548
549 pfind() { #find *$1* in $PATH
550 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
551 local pathArray
552 IFS=: pathArray=($PATH); unset IFS
553 find "${pathArray[@]}" -iname "*$1*"
554 }
555
556
557 pwd() { # do pwd + some other info.
558 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
559 }
560
561
562 pwgen() { # generate a random password, with digits & punctuation and without
563 arg=${1:-50}
564 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
565 echo
566 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
567 echo
568 }
569
570 q() { # start / launch a program in the backround and redir output to null
571 "$@" &> /dev/null &
572 }
573
574
575
576 r() {
577 exit "$@" 2>/dev/null
578 }
579
580 # trash-restore lists everything that has been trashed at or below CWD
581 # This picks out files just in CWD, not subdirectories,
582 # which also match grep $1, usually use $1 for a time string
583 # which you get from running restore-trash once first
584 pick-trash() {
585 local name x ask
586 local nth=1
587 # last condition is to not ask again for ones we skipped
588 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
589 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
590 name="$(echo "$name" | head -n $nth | tail -n 1 )"
591 read -p "$name [Y/n] " ask
592 if [[ ! $ask || $ask == [Yy] ]]; then
593 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
594 echo $x | restore-trash > /dev/null
595 elif [[ $ask == [Nn] ]]; then
596 nth=$((nth+1))
597 else
598 return
599 fi
600 done
601 }
602
603 # rsync, root is required to keep permissions right.
604 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
605 # --no-times --delete
606 # basically, make an exact copy, use checksums instead of file times to be more accurate
607 rl() { rsync -ahvic --delete "$@"; }
608 # don't delete files on the target end which do not exist on the original end:
609 rld() { rsync -ahvic "$@"; }
610 complete -F _rsync -o nospace rld rlt fl
611 # rl without preserving modification time. for some reason I had this as default before.
612 # perhaps that reason will come up again and I will document it.
613 rlt() { rsync -ahvic --delete --no-t "$@"; }
614
615
616
617 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
618 sb() {
619 local SUDOD="$PWD"
620 sudo -i bash -c "$@"
621 }
622 complete -F _root_command s sb
623
624 # use -ll, less secure but faster.
625 srm () {
626 command srm -ll "$@"
627 }
628
629 # sudo redo. be aware, this command may not work right on strange distros or earlier software
630 sr() {
631 if [[ $# == 0 ]]; then
632 sudo -E bash -c -l "$(history -p '!!')"
633 else
634 echo this command redos last history item. no argument is accepted
635 fi
636 }
637
638
639
640 # log with script. timing is $1.t and script is $1.s
641 # -l to save to ~/typescripts/
642 # -t to add a timestamp to the filenames
643 slog() {
644 local logdir do_stamp arg_base
645 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
646 logdir="/a/dt/"
647 do_stamp=false
648 while getopts "lt" option
649 do
650 case $option in
651 l ) arg_base=$logdir ;;
652 t ) do_stamp=true ;;
653 esac
654 done
655 shift $(($OPTIND - 1))
656 arg_base+=$1
657 [[ -e $logdir ]] || mkdir -p $logdir
658 $do_stamp && arg_base+=$(date +%F.%T%z)
659 script -t $arg_base.s 2> $arg_base.t
660 }
661 splay() { # script replay
662 #logRoot="$HOME/typescripts/"
663 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
664 scriptreplay "$1.t" "$1.s"
665 }
666
667
668
669 # timer in minutes
670 tm() {
671 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
672 }
673
674
675 ts() { # start editing a new file
676 [[ $# != 1 ]] && echo "I need a filename." && return 1
677 local quiet
678 if [[ $- != *i* ]]; then
679 quiet=true
680 fi
681 if [[ $1 == *.c ]]; then
682 e '#include <stdio.h>' >"$1"
683 e '#include <stdlib.h>' >>"$1"
684 e 'int main(int argc, char * argv[]) {' >>"$1"
685 e ' printf( "hello world\n");' >>"$1"
686 e ' return 0;' >>"$1"
687 e '}' >>"$1"
688 e "${1%.c}: $1" > Makefile
689 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
690 e "#!/bin/bash" >run.sh
691 e "./${1%.c}" >>run.sh
692 chmod +x run.sh
693 elif [[ $1 == *.java ]]; then
694 e "public class ${1%.*} {" >"$1"
695 e ' public static void main(String[] args) {' >>"$1"
696 e ' System.out.println("Hello, world!");' >>"$1"
697 e ' }' >>"$1"
698 e '}' >>"$1"
699
700 else
701 echo "#!/bin/bash" > "$1"
702 chmod +x "$1"
703 fi
704 [[ $quiet ]] || g "$1"
705
706 }
707
708 tx() { # toggle set -x, and the prompt so it doesn't spam
709 if [[ $- == *x* ]]; then
710 set +x
711 PROMPT_COMMAND=prompt_command
712 else
713 unset PROMPT_COMMAND
714 PS1="\w \$ "
715 set -x
716 fi
717 }
718
719
720
721
722 if [[ $OS == Windows_NT ]]; then
723 # cygstart wrapper
724 cs() {
725 cygstart "$@" &
726 }
727 xp() {
728 explorer.exe .
729 }
730 # launch
731 o() {
732 local x=(*$1*)
733 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
734 cygstart *$1* &
735 }
736 else
737 o() {
738 if type gvfs-open &> /dev/null ; then
739 gvfs-open "$@"
740 else
741 xdg-open "$@"
742 fi
743 # another alternative is run-mailcap
744 }
745 fi
746
747
748 # todo, update this
749 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
750
751
752
753 hl() { # history limit. Write extra history to archive file.
754 local max_lines linecount tempfile prune_lines
755 local harchive="${HISTFILE}_archive"
756 for x in "$HISTFILE" "$harchive"; do
757 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
758 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
759 echo "error in hl: history file \$x:$x no good"
760 return 1
761 fi
762 done
763 history -a # save history
764 max_lines=$HISTFILELINES
765 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
766 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
767 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
768 if (($linecount > $max_lines)); then
769 prune_lines=$(($linecount - $max_lines))
770 head -n $prune_lines "$HISTFILE" >> "$harchive" \
771 && sed -ie "1,${prune_lines}d" $HISTFILE
772 fi
773 }
774
775 if [[ $- == *i* ]]; then
776 # commands to run when bash exits normally
777 trap "hl; smh" EXIT
778 fi
779
780
781 # temporary variables to test colorization
782 # some copied from gentoo /etc/bash/bashrc,
783 use_color=false
784 # dircolors --print-database uses its own built-in database
785 # instead of using /etc/DIR_COLORS. Try to use the external file
786 # first to take advantage of user additions.
787 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
788 match_lhs=""
789 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
790 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
791 [[ -z ${match_lhs} ]] \
792 && type -P dircolors >/dev/null \
793 && match_lhs=$(dircolors --print-database)
794 # test if our $TERM is in the TERM values in dircolor
795 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
796
797
798 if ${use_color} && [[ $- == *i* ]]; then
799
800 if [[ $XTERM_VERSION == Cygwin* ]]; then
801 get_term_color() {
802 for x in "$@"; do
803 case $x in
804 underl) echo -n $'\E[4m' ;;
805 bold) echo -n $'\E[1m' ;;
806 red) echo -n $'\E[31m' ;;
807 green) echo -n $'\E[32m' ;;
808 blue) echo -n $'\E[34m' ;;
809 cyan) echo -n $'\E[36m' ;;
810 yellow) echo -n $'\E[33m' ;;
811 purple) echo -n $'\E[35m' ;;
812 nocolor) echo -n $'\E(B\E[m' ;;
813 esac
814 done
815 }
816
817 else
818 get_term_color() {
819 for x in "$@"; do
820 case $x in
821 underl) echo -n $(tput smul) ;;
822 bold) echo -n $(tput bold) ;;
823 red) echo -n $(tput setaf 1) ;;
824 green) echo -n $(tput setaf 2) ;;
825 blue) echo -n $(tput setaf 4) ;;
826 cyan) echo -n $(tput setaf 6) ;;
827 yellow) echo -n $(tput setaf 3) ;;
828 purple) echo -n $(tput setaf 5) ;;
829 nocolor) echo -n $(tput sgr0) ;; # no font attributes
830 esac
831 done
832 }
833 fi
834 else
835 get_term_color() {
836 :
837 }
838 fi
839 # Try to keep environment pollution down, EPA loves us.
840 unset safe_term match_lhs use_color
841
842
843
844
845
846
847 ###############
848 # prompt ######
849 ###############
850
851
852 if [[ $- == *i* ]]; then
853 # git branch/status prompt function
854 if [[ $OS != Windows_NT ]]; then
855 GIT_PS1_SHOWDIRTYSTATE=true
856 fi
857 # arch source location
858 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
859 # fedora/debian source
860 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
861
862 # in case we didn't source git-prompt.sh
863 if ! declare -f __git_ps1 > /dev/null; then
864 __git_ps1() {
865 :
866 }
867 fi
868
869 # this needs to come before next ps1 stuff
870 # this stuff needs bash 4, feb 2009,
871 # old enough to no longer condition on $BASH_VERSION anymore
872 shopt -s autocd
873 shopt -s dirspell
874 PS1='\w'
875 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
876 PROMPT_DIRTRIM=2
877 bind -m vi-command B:shell-backward-word
878 bind -m vi-command W:shell-forward-word
879 fi
880
881 if [[ $SSH_CLIENT ]]; then
882 PS1="\h $PS1"
883 fi
884
885 prompt_command() {
886 local return=$? # this MUST COME FIRST
887 local psc pst
888 local ps_char ps_color
889 unset IFS
890 history -a # save history
891 history -n # read any new history
892 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
893 # from the screen man page
894 if [[ $TERM == screen* ]]; then
895 local title_escape="\033]..2;"
896 else
897 local title_escape="\033]0;"
898 fi
899 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
900 fi
901
902 case $return in
903 0) ps_color="$(get_term_color blue)"
904 ps_char='\$'
905 ;;
906 1) ps_color="$(get_term_color green)"
907 ps_char="$return \\$"
908 ;;
909 *) ps_color="$(get_term_color yellow)"
910 ps_char="$return \\$"
911 ;;
912 esac
913 if [[ ! -O . ]]; then # not owner
914 if [[ -w . ]]; then # writable
915 ps_color="$(get_term_color bold red)"
916 else
917 ps_color="$(get_term_color bold green)"
918 fi
919 fi
920 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
921 }
922 PROMPT_COMMAND=prompt_command
923 fi
924
925
926 ###########################################
927 # stuff that makes sense to be at the end #
928 ###########################################
929 if [[ "$SUDOD" ]]; then
930 cd "$SUDOD"
931 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
932 cd /a
933 fi
934
935
936 # best practice
937 unset IFS
938
939
940 # if someone exported $SOE, catch errors
941 if [[ $SOE ]]; then
942 errcatch
943 fi