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