3 # redirect output to log file
8 # The default of sourcing this file for all ssh commands is a buggy practice. Normally, this
9 # file is not sourced when a script is run, and we should follow that convention.
10 # we can override with ssh -t which sets $SSH_TTY, which we can detect
11 if [[ $SSH_CONNECTION ]] \
14 && [[ $- != *i* ]]; then
18 # Side note on ssh. Command lines and env variables sent across ssh are strictly limited.
19 # If we did want to easily pass info, we could override an obscure unused LC_var
20 # Or we could set SendEnv and AcceptEnv ssh vars, or we could transfer a file.
28 for x in $HOME/bin/bash-programs-by-ian/repos/*/*-function; do
32 source $HOME/bin/bash_private # so I can share my bashrc
33 source $HOME/path_add-function
44 # remove gnome keyring warning messages
45 # there is probably a more proper way, but I didn't find any easily on google
46 unset GNOME_KEYRING_CONTROL
48 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
50 #use extra globing features. See man bash, search extglob.
52 #include .files when globbing.
55 # disabled because it is broken with bash_completion package. It is a known bug they hope to fix.
56 # When a glob expands to nothing, make it an empty string instead of the literal characters.
59 # make tab on an empty line do nothing
60 shopt -s no_empty_cmd_completion
64 # http://bash-completion.alioth.debian.org/
65 # i was using the git version for a while. not bothering now.
66 # seems a bit inefficient to source it here, and let the system bash
67 # scripts source it too. todo, investigate if I am super bored sometime
68 if [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
69 . /usr/share/bash-completion/bash_completion
72 # fix spelling errors for cd, only in interactive shell
74 # append history instead of overwritting it
76 # for compatibility, per gentoo/debian bashrc
78 # attempt to save multiline single commands as single history entries.
81 if [[ $- == *i* ]]; then
82 # for readline-complete.el
83 if [[ $INSIDE_EMACS ]]; then
84 bind 'set horizontal-scroll-mode on'
85 bind 'set print-completions-horizontally on'
89 # debconf occasionally spews messages about wanting to initialize dialog
90 # and falling back to readline, since our terminal is dumb, then does nothing,
91 # This is a long standing bug. Here is the fix.
92 if [[ $DISPLAY ]]; then
93 export DEBIAN_FRONTEND=gnome
95 export DEBIAN_FRONTEND=readline
98 stty werase undef lnext undef stop undef start undef
99 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
100 # gnome-terminal, overridden by bash, or disabled by the system
102 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
103 if [[ $TERM == "xterm" ]]; then
104 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
105 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
107 bind '"\eOc": shell-forward-word'
108 bind '"\eOd": shell-backward-word'
115 # history number. History expansion is good.
117 # history file size limit, set to unlimited.
119 # max commands 1 session can append to history
121 # my history size limit based on lines
122 HISTFILELINES=1000000
123 # this needs to be different from the derault because
124 # default HISTFILESIZE is 500 and could clobber our history
126 HISTTIMEFORMAT="%I:%M %p %m/%d "
127 # consecutive duplicate lines don't go in history
130 export BC_LINE_LENGTH=0
132 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
133 path_add $HOME/bin/bash-programs-by-ian/utils
134 # note, if I use a machine I don't want files readable by all users, set
135 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
146 if [[ $- == *i* ]]; then
151 # remove any default aliases for these
152 alias ls > /dev/null 2>&1 && unalias ls
153 alias ll > /dev/null 2>&1 && unalias ll
154 alias grep > /dev/null 2>&1 && unalias grep
158 command mkdir -p "$@"
163 complete -A stopped -P '"%' -S '"' d
168 # note: gksudo is recommended for X apps because it does not set the
169 # home directory to the same.
171 if [[ $- == *i* ]]; then
172 # extra space at the end allows aliases to work
173 alias s='SUDOD="$PWD" sudo -i '
176 if [[ $EUID != 0 || $1 == -* ]]; then
187 if [[ $OS == Windows_NT ]]; then
188 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
190 alias j='command cygpath'
191 alias t='command cygstart'
192 alias cygstart='echo be quick, use the alias "t" instead :\)'
193 alias cygpath='echo be quick, use the alias "j" instead :\)'
198 #####################
200 #####################
214 if type ack-grep >/dev/null 2>&1; then
220 grep -i --binary-files=without-match --color=auto "$@"
224 grep -ri --binary-files=without-match --color=auto "$@"
232 calc() { echo "scale=3; $*" | bc -l; }
235 if [[ $1 == .. ]]; then
236 echo 'be cool, use the alias ".." instead :)'
242 # makes it so chown -R symlink affects the symlink and its target.
244 if [[ $1 == -R ]]; then
246 command chown -h "$@"
248 command chown -RH "$@"
258 if [[ $# == 0 ]]; then
259 cp /a/bin/data/COPYING .
261 cp /a/bin/data/COPYING "$@"
267 diff --strip-trailing-cr -w "$@" # diff content
272 if [[ -f /etc/fedora-release ]]; then
275 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
281 date "+%A, %B %d, %r" "$@"
288 envload() { # load environment from a previous: export > file
289 local file=${1:-$HOME/.${USER}_env}
290 eval "$(export | sed 's/^declare -x/export -n/')"
291 while IFS= read -r line; do
292 # declare -x makes variables local to a function
293 eval ${line/#declare -x/export}
299 # havn't tested these:
300 #file cut copy and paste, like the text buffers :)
301 _fbufferinit() { # internal use by
302 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
303 rm -rf "$my_f_tempdir"/*
307 cp "$@" "$my_f_tempdir"/
311 mv "$@" "$my_f_tempdir"/
313 fpst() { # file paste
314 [[ $2 ]] && { echo too many arguments; return 1; }
316 cp "$my_f_tempdir"/* "$target"
320 # find array. make an array of file names found by find into $x
321 # argument: find arguments
322 # return: find results in an array $x
324 while read -rd ''; do
326 done < <(find "$@" -print0);
330 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
331 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
333 gitroot || return 1 # function to set gitroot
335 git symbolic-ref HEAD refs/heads/$1
341 firefox -P default "$@" >/dev/null 2>&1
345 firefox -P alt "$@" >/dev/null 2>&1
352 # horizontal row. used to break up output
353 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
359 # modified from ~/local/bin/git-completion.bash
360 # other completion commands are mostly taken from bash_completion package
361 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
362 || complete -o default -o nospace -F _git i
367 find . -iname '*'"$*"'*'
373 if [[ $PWD == /[iap] ]]; then
374 command ls -A --color=auto -I lost+found "$@"
376 command ls -A --color=auto "$@"
381 lld() { ll -d "$@"; }
384 low() { # make filenames all lowercase
387 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
388 [[ $y != $x ]] && mv "$x" "$y"
393 lower() { # make first letter of filenames lowercase.
396 if [[ ${x::1} == [A-Z] ]]; then
397 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
398 safe_rename "$x" "$y"
404 if [[ $# != 2 ]]; then
405 echo safe_rename error: $# args, need 2 >2
407 elif [[ $1 != $2 ]]; then
409 echo Cannot rename "$1" to "$2" as it already exists.
420 safe_rename "$x" "$y"
424 # force symbolic link creation.
425 # trash-put any existing files where links would be created.
426 # mkdir -p the directory containing the link(s) if needed.
427 # then do ln -s -- "$@"
429 if [[ $# -gt 2 && ! -d ${!#} ]]; then
432 if [[ $# -gt 1 && -d ${!#} ]]; then
435 for x in "${@:1:$(($#-1))}"; do # all but last arg
436 # remove any trailing slashes
438 # remove any leading directory components
440 te "$x" && trash-put "$x"
443 elif [[ $# -eq 2 ]]; then
446 elif [[ ! -d $(getdir "$2") ]]; then
447 mkdir -p $(getdir "$2")
450 te "${1##*/}" && rm "${1##*/}"
458 # aliases would be much more compact, but they can't be used as ssh commands
459 # also, to be used in a script, you need -i which prints annoying
460 # warnings. instead, use -l in a script to source this file
461 if type -p yum > /dev/null; then
463 if [[ $EUID == 0 ]]; then
470 if [[ $EUID == 0 ]]; then
473 sudo yum -y install "$@"
477 if [[ $EUID == 0 ]]; then
485 if [[ $EUID == 0 ]]; then
492 if [[ $EUID == 0 ]]; then
493 aptitude -y install "$@"
495 sudo aptitude -y install "$@"
499 if [[ $EUID == 0 ]]; then
502 sudo aptitude search "$@"
512 [[ -e "$x" || -L "$x" ]] || ret=1
518 # fix root file ownership for FILE argument.
519 # check if parent or grandparent is not root and if the dir of FILE is also
520 # owned by that user, and change ownership to that user
523 if [[ $EUID == 0 ]]; then
524 [[ -e $1 ]] || touch $1
525 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
527 argdir=$(getdir "$1")
528 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
529 if ! chown "--reference=$argdir" "$1"; then
530 echo failed to fix bad ownership file permissons
538 pfind() { #find *$1* in $PATH
539 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
541 IFS=: pathArray=($PATH); unset IFS
542 find "${pathArray[@]}" -iname "*$1*"
546 pwd() { # do pwd + some other info.
547 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
551 pwgen() { # generate a random password, with digits & punctuation and without
553 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
555 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
559 q() { # start / launch a program in the backround and redir output to null
569 # rsync, root is required to keep permissions right.
570 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
571 # --no-times --delete
572 # basically, make an exact copy, use checksums instead of file times to be more accurate
573 rl() { rsync -ahvic --delete "$@"; }
574 # don't delete files on the target end which do not exist on the original end:
575 rld() { rsync -ahvic "$@"; }
576 complete -F _rsync -o nospace rld rlt fl
577 # rl without preserving modification time. for some reason I had this as default before.
578 # perhaps that reason will come up again and I will document it.
579 rlt() { rsync -ahvic --delete --no-t "$@"; }
583 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
588 complete -F _root_command s sb
590 # use -ll, less secure but faster.
595 # sudo redo. be aware, this command may not work right on strange distros or earlier software
597 if [[ $# == 0 ]]; then
598 sudo -E bash -c -l "$(history -p '!!')"
600 echo this command redos last history item. no argument is accepted
606 # log with script. timing is $1.t and script is $1.s
607 # -l to save to ~/typescripts/
608 # -t to add a timestamp to the filenames
610 local logdir do_stamp arg_base
611 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
614 while getopts "lt" option
617 l ) arg_base=$logdir ;;
621 shift $(($OPTIND - 1))
623 [[ -e $logdir ]] || mkdir -p $logdir
624 $do_stamp && arg_base+=$(date +%F.%T%z)
625 script -t $arg_base.s 2> $arg_base.t
627 splay() { # script replay
628 #logRoot="$HOME/typescripts/"
629 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
630 scriptreplay "$1.t" "$1.s"
637 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
641 ts() { # start editing a new file
642 [[ $# != 1 ]] && echo "I need a filename." && return 1
644 if [[ $- != *i* ]]; then
647 if [[ $1 == *.c ]]; then
648 e '#include <stdio.h>' >"$1"
649 e '#include <stdlib.h>' >>"$1"
650 e 'int main(int argc, char * argv[]) {' >>"$1"
651 e ' printf( "hello world\n");' >>"$1"
652 e ' return 0;' >>"$1"
654 e "${1%.c}: $1" > Makefile
655 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
656 e "#!/bin/bash" >run.sh
657 e "./${1%.c}" >>run.sh
659 elif [[ $1 == *.java ]]; then
660 e "public class ${1%.*} {" >"$1"
661 e ' public static void main(String[] args) {' >>"$1"
662 e ' System.out.println("Hello, world!");' >>"$1"
667 echo "#!/bin/bash" > "$1"
670 [[ $quiet ]] || g "$1"
674 tx() { # toggle set -x, and the prompt so it doesn't spam
675 if [[ $- == *x* ]]; then
677 PROMPT_COMMAND=prompt_command
688 if [[ $OS == Windows_NT ]]; then
699 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
704 if type gvfs-open &> /dev/null ; then
709 # another alternative is run-mailcap
715 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
719 hl() { # history limit. Write extra history to archive file.
720 local max_lines linecount tempfile
721 for x in $HISTFILE ${HISTFILE}_archive; do
722 if [[ -e $x && ! -w $x ]]; then
723 echo "error: history file $x is not writable."
729 max_lines=$(($1 * 2)) # 2 lines for every history command
731 max_lines=$HISTFILELINES
733 linecount=$(wc -l < $HISTFILE)
734 linecount=${linecount:-0}
735 if (($linecount > $max_lines)); then
736 prune_lines=$(($linecount - $max_lines))
738 [[ $tempfile ]] || { echo mktemp failed; return 1; }
739 head -$prune_lines $HISTFILE >> ${HISTFILE}a \
740 && sed -ie "1,${prune_lines}d" $HISTFILE
743 perm_fix ${HISTFILE}_archive
746 # commands to run when bash exits normally
750 # temporary variables to test colorization
751 # some copied from gentoo /etc/bash/bashrc,
753 # dircolors --print-database uses its own built-in database
754 # instead of using /etc/DIR_COLORS. Try to use the external file
755 # first to take advantage of user additions.
756 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
758 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
759 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
760 [[ -z ${match_lhs} ]] \
761 && type -P dircolors >/dev/null \
762 && match_lhs=$(dircolors --print-database)
763 # test if our $TERM is in the TERM values in dircolor
764 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
767 if ${use_color} && [[ $- == *i* ]]; then
769 if [[ $XTERM_VERSION == Cygwin* ]]; then
773 underl) echo -n $'\E[4m' ;;
774 bold) echo -n $'\E[1m' ;;
775 red) echo -n $'\E[31m' ;;
776 green) echo -n $'\E[32m' ;;
777 blue) echo -n $'\E[34m' ;;
778 cyan) echo -n $'\E[36m' ;;
779 yellow) echo -n $'\E[33m' ;;
780 purple) echo -n $'\E[35m' ;;
781 nocolor) echo -n $'\E(B\E[m' ;;
790 underl) echo -n $(tput smul) ;;
791 bold) echo -n $(tput bold) ;;
792 red) echo -n $(tput setaf 1) ;;
793 green) echo -n $(tput setaf 2) ;;
794 blue) echo -n $(tput setaf 4) ;;
795 cyan) echo -n $(tput setaf 6) ;;
796 yellow) echo -n $(tput setaf 3) ;;
797 purple) echo -n $(tput setaf 5) ;;
798 nocolor) echo -n $(tput sgr0) ;; # no font attributes
808 # Try to keep environment pollution down, EPA loves us.
809 unset safe_term match_lhs use_color
821 if [[ $- == *i* ]]; then
822 # git branch/status prompt function
823 if [[ $OS != Windows_NT ]]; then
824 GIT_PS1_SHOWDIRTYSTATE=true
826 # arch source location
827 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
828 # fedora/debian source
829 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
831 # in case we didn't source git-prompt.sh
832 if ! declare -f __git_ps1 > /dev/null; then
838 # this needs to come before next ps1 stuff
839 if [[ $BASH_VERSION == [456789]* ]]; then
844 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
846 bind -m vi-command B:shell-backward-word
847 bind -m vi-command W:shell-forward-word
853 if [[ $SSH_CLIENT ]]; then
858 local return=$? # this MUST COME FIRST
860 local ps_char ps_color
862 history -a # save history
863 history -n # read any new history
864 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
865 # from the screen man page
866 if [[ $TERM == screen* ]]; then
867 local title_escape="\033]..2;"
869 local title_escape="\033]0;"
871 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
875 0) ps_color="$(get_term_color blue)"
878 1) ps_color="$(get_term_color green)"
881 *) ps_color="$(get_term_color yellow)"
885 if [[ ! -O . ]]; then # not owner
886 if [[ -w . ]]; then # writable
887 ps_color="$(get_term_color bold red)"
889 ps_color="$(get_term_color bold green)"
892 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
894 PROMPT_COMMAND=prompt_command
898 ###########################################
899 # stuff that makes sense to be at the end #
900 ###########################################
901 if [[ "$SUDOD" ]]; then
903 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
912 # if someone exported $SOE, catch errors