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