3 # redirect output to log file
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.
19 [[ $- != *i* && ! $SSH_CONNECTION ]] && export BASH_LOGIN_SHELL=true
21 if [[ $SSH_CONNECTION ]] \
24 && [[ ! $BASH_LOGIN_SHELL == true ]] \
25 && [[ $- != *i* ]]; then
37 for x in $HOME/bin/bash-programs-by-ian/repos/*/*-function; do
41 source $HOME/bin/semi-private # so I can share my bashrc
42 source $HOME/path_add-function
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
57 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
59 #use extra globing features. See man bash, search extglob.
61 #include .files when globbing.
64 # disabled because it is broken with bash_completion package. It is a known bug they hope to fix.
65 # When a glob expands to nothing, make it an empty string instead of the literal characters.
68 # make tab on an empty line do nothing
69 shopt -s no_empty_cmd_completion
73 # http://bash-completion.alioth.debian.org/
74 # i was using the git version for a while for a bug fix.
75 # it's made it into distros now
76 # usually this is sourced by the system already,
77 # but I check just incase
78 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
79 . /usr/share/bash-completion/bash_completion
82 # fix spelling errors for cd, only in interactive shell
84 # append history instead of overwritting it
86 # for compatibility, per gentoo/debian bashrc
88 # attempt to save multiline single commands as single history entries.
92 if [[ $INSIDE_EMACS ]]; then
96 # for readline-complete.el
101 if [[ $- == *i* ]]; then
102 # for readline-complete.el
103 if [[ $INSIDE_EMACS ]]; then
104 bind 'set horizontal-scroll-mode on'
105 bind 'set print-completions-horizontally on'
106 bind '"\C-i": self-insert'
108 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
109 if [[ $TERM == "xterm" ]]; then
110 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
111 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
113 bind '"\eOc": shell-forward-word'
114 bind '"\eOd": shell-backward-word'
116 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
117 # gnome-terminal, overridden by bash, or disabled by the system
118 stty werase undef lnext undef stop undef start undef
125 # history number. History expansion is good.
127 # history file size limit, set to unlimited.
128 # this needs to be different from the default because
129 # default HISTFILESIZE is 500 and could clobber our history
131 # max commands 1 session can append/read from history
133 # my own history size limit based on lines
134 HISTFILELINES=1000000
136 # the time format display when doing the history command
137 # also, setting this makes the history file record time
138 # of each command as seconds from the epoch
139 HISTTIMEFORMAT="%I:%M %p %m/%d "
140 # consecutive duplicate lines don't go in history
141 HISTCONTROL=ignoredups
142 # just defensively unsetting this
143 # this var can replace HISTCONTROL to do more flexible things like
144 # not saving single char history items or specific names
147 export BC_LINE_LENGTH=0
149 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
150 path_add $HOME/bin/bash-programs-by-ian/utils
151 # note, if I use a machine I don't want files readable by all users, set
152 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
163 if [[ $- == *i* ]]; then
168 # remove any default aliases for these
169 alias ls > /dev/null 2>&1 && unalias ls
170 alias ll > /dev/null 2>&1 && unalias ll
171 alias grep > /dev/null 2>&1 && unalias grep
175 command mkdir -p "$@"
180 complete -A stopped -P '"%' -S '"' d
185 # note: gksudo is recommended for X apps because it does not set the
186 # home directory to the same.
188 if [[ $- == *i* ]]; then
189 # extra space at the end allows aliases to work
190 alias s='SUDOD="$PWD" sudo -i '
193 if [[ $EUID != 0 || $1 == -* ]]; then
204 if [[ $OS == Windows_NT ]]; then
205 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
207 alias j='command cygpath'
208 alias t='command cygstart'
209 alias cygstart='echo be quick, use the alias "t" instead :\)'
210 alias cygpath='echo be quick, use the alias "j" instead :\)'
215 #####################
217 #####################
231 if type ack-grep >/dev/null 2>&1; then
237 grep -i --binary-files=without-match --color=auto "$@"
241 grep -ri --binary-files=without-match --color=auto "$@"
247 calc() { echo "scale=3; $*" | bc -l; }
250 # makes it so chown -R symlink affects the symlink and its target.
252 if [[ $1 == -R ]]; then
254 command chown -h "$@"
256 command chown -RH "$@"
266 if [[ $# == 0 ]]; then
267 cp /a/bin/data/COPYING .
269 cp /a/bin/data/COPYING "$@"
275 diff --strip-trailing-cr -w "$@" # diff content
280 if [[ -f /etc/fedora-release ]]; then
283 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
289 date "+%A, %B %d, %r" "$@"
296 envload() { # load environment from a previous: export > file
297 local file=${1:-$HOME/.${USER}_env}
298 eval "$(export | sed 's/^declare -x/export -n/')"
299 while IFS= read -r line; do
300 # declare -x makes variables local to a function
301 eval ${line/#declare -x/export}
307 # havn't tested these:
308 #file cut copy and paste, like the text buffers :)
309 _fbufferinit() { # internal use by
310 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
311 rm -rf "$my_f_tempdir"/*
315 cp "$@" "$my_f_tempdir"/
319 mv "$@" "$my_f_tempdir"/
321 fpst() { # file paste
322 [[ $2 ]] && { echo too many arguments; return 1; }
324 cp "$my_f_tempdir"/* "$target"
328 # find array. make an array of file names found by find into $x
329 # argument: find arguments
330 # return: find results in an array $x
332 while read -rd ''; do
334 done < <(find "$@" -print0);
338 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
339 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
341 gitroot || return 1 # function to set gitroot
343 git symbolic-ref HEAD refs/heads/$1
349 firefox -P default "$@" >/dev/null 2>&1
353 firefox -P alt "$@" >/dev/null 2>&1
360 # horizontal row. used to break up output
361 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
367 # modified from ~/local/bin/git-completion.bash
368 # other completion commands are mostly taken from bash_completion package
369 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
370 || complete -o default -o nospace -F _git i
375 find . -iname '*'"$*"'*'
381 if [[ $PWD == /[iap] ]]; then
382 command ls -A --color=auto -I lost+found "$@"
384 command ls -A --color=auto "$@"
389 lld() { ll -d "$@"; }
392 low() { # make filenames all lowercase
395 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
396 [[ $y != $x ]] && mv "$x" "$y"
401 lower() { # make first letter of filenames lowercase.
404 if [[ ${x::1} == [A-Z] ]]; then
405 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
406 safe_rename "$x" "$y"
412 if [[ $# != 2 ]]; then
413 echo safe_rename error: $# args, need 2 >2
415 elif [[ $1 != $2 ]]; then
417 echo Cannot rename "$1" to "$2" as it already exists.
428 safe_rename "$x" "$y"
432 # force symbolic link creation.
433 # trash-put any existing files where links would be created.
434 # mkdir -p the directory containing the link(s) if needed.
435 # then do ln -s -- "$@"
437 if [[ $# -gt 2 && ! -d ${!#} ]]; then
440 if [[ $# -gt 1 && -d ${!#} ]]; then
443 for x in "${@:1:$(($#-1))}"; do # all but last arg
444 # remove any trailing slashes
446 # remove any leading directory components
448 te "$x" && trash-put "$x"
451 elif [[ $# -eq 2 ]]; then
454 elif [[ ! -d $(getdir "$2") ]]; then
455 mkdir -p $(getdir "$2")
458 te "${1##*/}" && rm "${1##*/}"
466 # aliases would be much more compact, but they can't be used as ssh commands
467 # also, to be used in a script, you need -i which prints annoying
468 # warnings. instead, use -l in a script to source this file
469 if type -p yum > /dev/null; then
471 if [[ $EUID == 0 ]]; then
478 if [[ $EUID == 0 ]]; then
481 sudo yum -y install "$@"
485 if [[ $EUID == 0 ]]; then
493 if [[ $EUID == 0 ]]; then
500 if [[ $EUID == 0 ]]; then
501 aptitude -y install "$@"
503 sudo aptitude -y install "$@"
507 # scratch a very annoying itch.
508 # package description width as wide as the screen, and package name field small
509 # aptitude manual can't figure out how wide emacs terminal is,
510 # of course it doesn't consult the $COLUMNS variable...
511 # and in a normal terminal, it makes the package name field ridiculously big
512 # also, remove that useless dash before the description
513 if [[ $EUID == 0 ]]; then
514 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
516 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
522 # test existence / exists
526 [[ -e "$x" || -L "$x" ]] || ret=1
532 # fix root file ownership for FILE argument.
533 # check if parent or grandparent is not root and if the dir of FILE is also
534 # owned by that user, and change ownership to that user
537 if [[ $EUID == 0 ]]; then
539 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
540 argdir=$(getdir "$1")
541 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
542 if ! chown "--reference=$argdir" "$1"; then
543 echo failed to fix bad ownership file permissons
551 pfind() { #find *$1* in $PATH
552 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
554 IFS=: pathArray=($PATH); unset IFS
555 find "${pathArray[@]}" -iname "*$1*"
559 pwd() { # do pwd + some other info.
560 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
564 pwgen() { # generate a random password, with digits & punctuation and without
566 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
568 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
572 q() { # start / launch a program in the backround and redir output to null
582 # rsync, root is required to keep permissions right.
583 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
584 # --no-times --delete
585 # basically, make an exact copy, use checksums instead of file times to be more accurate
586 rl() { rsync -ahvic --delete "$@"; }
587 # don't delete files on the target end which do not exist on the original end:
588 rld() { rsync -ahvic "$@"; }
589 complete -F _rsync -o nospace rld rlt fl
590 # rl without preserving modification time. for some reason I had this as default before.
591 # perhaps that reason will come up again and I will document it.
592 rlt() { rsync -ahvic --delete --no-t "$@"; }
596 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
601 complete -F _root_command s sb
603 # use -ll, less secure but faster.
608 # sudo redo. be aware, this command may not work right on strange distros or earlier software
610 if [[ $# == 0 ]]; then
611 sudo -E bash -c -l "$(history -p '!!')"
613 echo this command redos last history item. no argument is accepted
619 # log with script. timing is $1.t and script is $1.s
620 # -l to save to ~/typescripts/
621 # -t to add a timestamp to the filenames
623 local logdir do_stamp arg_base
624 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
627 while getopts "lt" option
630 l ) arg_base=$logdir ;;
634 shift $(($OPTIND - 1))
636 [[ -e $logdir ]] || mkdir -p $logdir
637 $do_stamp && arg_base+=$(date +%F.%T%z)
638 script -t $arg_base.s 2> $arg_base.t
640 splay() { # script replay
641 #logRoot="$HOME/typescripts/"
642 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
643 scriptreplay "$1.t" "$1.s"
650 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
654 ts() { # start editing a new file
655 [[ $# != 1 ]] && echo "I need a filename." && return 1
657 if [[ $- != *i* ]]; then
660 if [[ $1 == *.c ]]; then
661 e '#include <stdio.h>' >"$1"
662 e '#include <stdlib.h>' >>"$1"
663 e 'int main(int argc, char * argv[]) {' >>"$1"
664 e ' printf( "hello world\n");' >>"$1"
665 e ' return 0;' >>"$1"
667 e "${1%.c}: $1" > Makefile
668 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
669 e "#!/bin/bash" >run.sh
670 e "./${1%.c}" >>run.sh
672 elif [[ $1 == *.java ]]; then
673 e "public class ${1%.*} {" >"$1"
674 e ' public static void main(String[] args) {' >>"$1"
675 e ' System.out.println("Hello, world!");' >>"$1"
680 echo "#!/bin/bash" > "$1"
683 [[ $quiet ]] || g "$1"
687 tx() { # toggle set -x, and the prompt so it doesn't spam
688 if [[ $- == *x* ]]; then
690 PROMPT_COMMAND=prompt_command
701 if [[ $OS == Windows_NT ]]; then
712 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
717 if type gvfs-open &> /dev/null ; then
722 # another alternative is run-mailcap
728 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
732 hl() { # history limit. Write extra history to archive file.
733 local max_lines linecount tempfile prune_lines
734 local harchive="${HISTFILE}_archive"
735 for x in "$HISTFILE" "$harchive"; do
736 if [[ ! $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
737 echo "error in hl: history file $x no good"
741 history -a # save history
742 max_lines=$HISTFILELINES
743 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
744 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
745 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
746 if (($linecount > $max_lines)); then
747 prune_lines=$(($linecount - $max_lines))
748 head -n $prune_lines "$HISTFILE" >> "$harchive" \
749 && sed -ie "1,${prune_lines}d" $HISTFILE
753 # commands to run when bash exits normally
757 # temporary variables to test colorization
758 # some copied from gentoo /etc/bash/bashrc,
760 # dircolors --print-database uses its own built-in database
761 # instead of using /etc/DIR_COLORS. Try to use the external file
762 # first to take advantage of user additions.
763 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
765 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
766 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
767 [[ -z ${match_lhs} ]] \
768 && type -P dircolors >/dev/null \
769 && match_lhs=$(dircolors --print-database)
770 # test if our $TERM is in the TERM values in dircolor
771 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
774 if ${use_color} && [[ $- == *i* ]]; then
776 if [[ $XTERM_VERSION == Cygwin* ]]; then
780 underl) echo -n $'\E[4m' ;;
781 bold) echo -n $'\E[1m' ;;
782 red) echo -n $'\E[31m' ;;
783 green) echo -n $'\E[32m' ;;
784 blue) echo -n $'\E[34m' ;;
785 cyan) echo -n $'\E[36m' ;;
786 yellow) echo -n $'\E[33m' ;;
787 purple) echo -n $'\E[35m' ;;
788 nocolor) echo -n $'\E(B\E[m' ;;
797 underl) echo -n $(tput smul) ;;
798 bold) echo -n $(tput bold) ;;
799 red) echo -n $(tput setaf 1) ;;
800 green) echo -n $(tput setaf 2) ;;
801 blue) echo -n $(tput setaf 4) ;;
802 cyan) echo -n $(tput setaf 6) ;;
803 yellow) echo -n $(tput setaf 3) ;;
804 purple) echo -n $(tput setaf 5) ;;
805 nocolor) echo -n $(tput sgr0) ;; # no font attributes
815 # Try to keep environment pollution down, EPA loves us.
816 unset safe_term match_lhs use_color
828 if [[ $- == *i* ]]; then
829 # git branch/status prompt function
830 if [[ $OS != Windows_NT ]]; then
831 GIT_PS1_SHOWDIRTYSTATE=true
833 # arch source location
834 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
835 # fedora/debian source
836 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
838 # in case we didn't source git-prompt.sh
839 if ! declare -f __git_ps1 > /dev/null; then
845 # this needs to come before next ps1 stuff
846 if [[ $BASH_VERSION == [456789]* ]]; then
851 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
853 bind -m vi-command B:shell-backward-word
854 bind -m vi-command W:shell-forward-word
860 if [[ $SSH_CLIENT ]]; then
865 local return=$? # this MUST COME FIRST
867 local ps_char ps_color
869 history -a # save history
870 history -n # read any new history
871 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
872 # from the screen man page
873 if [[ $TERM == screen* ]]; then
874 local title_escape="\033]..2;"
876 local title_escape="\033]0;"
878 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
882 0) ps_color="$(get_term_color blue)"
885 1) ps_color="$(get_term_color green)"
888 *) ps_color="$(get_term_color yellow)"
892 if [[ ! -O . ]]; then # not owner
893 if [[ -w . ]]; then # writable
894 ps_color="$(get_term_color bold red)"
896 ps_color="$(get_term_color bold green)"
899 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
901 PROMPT_COMMAND=prompt_command
905 ###########################################
906 # stuff that makes sense to be at the end #
907 ###########################################
908 if [[ "$SUDOD" ]]; then
910 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
919 # if someone exported $SOE, catch errors