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.
18 [[ $- != *i* && ! $SSH_CONNECTION ]] && export BASH_LOGIN_SHELL=true
19 if [[ $SSH_CONNECTION ]] \
22 && [[ ! $BASH_LOGIN_SHELL == true ]] \
23 && [[ $- != *i* ]]; then
35 for x in $HOME/bin/bash-programs-by-ian/repos/*/*-function; do
39 source $HOME/bin/semi-private # so I can share my bashrc
40 source $HOME/path_add-function
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
55 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
57 #use extra globing features. See man bash, search extglob.
59 #include .files when globbing.
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.
66 # make tab on an empty line do nothing
67 shopt -s no_empty_cmd_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
80 # fix spelling errors for cd, only in interactive shell
82 # append history instead of overwritting it
84 # for compatibility, per gentoo/debian bashrc
86 # attempt to save multiline single commands as single history entries.
90 if [[ $INSIDE_EMACS ]]; then
94 # for readline-complete.el
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'
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
111 bind '"\eOc": shell-forward-word'
112 bind '"\eOd": shell-backward-word'
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
123 # history number. History expansion is good.
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
129 # max commands 1 session can append/read from history
131 # my own history size limit based on lines
132 HISTFILELINES=1000000
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
145 export BC_LINE_LENGTH=0
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
161 if [[ $- == *i* ]]; then
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
173 command mkdir -p "$@"
178 complete -A stopped -P '"%' -S '"' d
183 # note: gksudo is recommended for X apps because it does not set the
184 # home directory to the same.
186 if [[ $- == *i* ]]; then
187 # extra space at the end allows aliases to work
188 alias s='SUDOD="$PWD" sudo -i '
191 if [[ $EUID != 0 || $1 == -* ]]; then
202 if [[ $OS == Windows_NT ]]; then
203 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
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 :\)'
213 #####################
215 #####################
229 if type ack-grep >/dev/null 2>&1; then
235 grep -i --binary-files=without-match --color=auto "$@"
239 grep -ri --binary-files=without-match --color=auto "$@"
245 calc() { echo "scale=3; $*" | bc -l; }
248 # makes it so chown -R symlink affects the symlink and its target.
250 if [[ $1 == -R ]]; then
252 command chown -h "$@"
254 command chown -RH "$@"
264 if [[ $# == 0 ]]; then
265 cp /a/bin/data/COPYING .
267 cp /a/bin/data/COPYING "$@"
273 diff --strip-trailing-cr -w "$@" # diff content
278 if [[ -f /etc/fedora-release ]]; then
281 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
287 date "+%A, %B %d, %r" "$@"
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}
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"/*
313 cp "$@" "$my_f_tempdir"/
317 mv "$@" "$my_f_tempdir"/
319 fpst() { # file paste
320 [[ $2 ]] && { echo too many arguments; return 1; }
322 cp "$my_f_tempdir"/* "$target"
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
330 while read -rd ''; do
332 done < <(find "$@" -print0);
336 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
337 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
339 gitroot || return 1 # function to set gitroot
341 git symbolic-ref HEAD refs/heads/$1
347 firefox -P default "$@" >/dev/null 2>&1
351 firefox -P alt "$@" >/dev/null 2>&1
358 # horizontal row. used to break up output
359 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
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
373 find . -iname '*'"$*"'*'
379 if [[ $PWD == /[iap] ]]; then
380 command ls -A --color=auto -I lost+found "$@"
382 command ls -A --color=auto "$@"
387 lld() { ll -d "$@"; }
390 low() { # make filenames all lowercase
393 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
394 [[ $y != $x ]] && mv "$x" "$y"
399 lower() { # make first letter of filenames lowercase.
402 if [[ ${x::1} == [A-Z] ]]; then
403 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
404 safe_rename "$x" "$y"
410 if [[ $# != 2 ]]; then
411 echo safe_rename error: $# args, need 2 >2
413 elif [[ $1 != $2 ]]; then
415 echo Cannot rename "$1" to "$2" as it already exists.
426 safe_rename "$x" "$y"
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 -- "$@"
435 if [[ $# -gt 2 && ! -d ${!#} ]]; then
438 if [[ $# -gt 1 && -d ${!#} ]]; then
441 for x in "${@:1:$(($#-1))}"; do # all but last arg
442 # remove any trailing slashes
444 # remove any leading directory components
446 te "$x" && trash-put "$x"
449 elif [[ $# -eq 2 ]]; then
452 elif [[ ! -d $(getdir "$2") ]]; then
453 mkdir -p $(getdir "$2")
456 te "${1##*/}" && rm "${1##*/}"
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
469 if [[ $EUID == 0 ]]; then
476 if [[ $EUID == 0 ]]; then
479 sudo yum -y install "$@"
483 if [[ $EUID == 0 ]]; then
491 if [[ $EUID == 0 ]]; then
498 if [[ $EUID == 0 ]]; then
499 aptitude -y install "$@"
501 sudo aptitude -y install "$@"
505 if [[ $EUID == 0 ]]; then
508 sudo aptitude search "$@"
514 # test existence / exists
518 [[ -e "$x" || -L "$x" ]] || ret=1
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
529 if [[ $EUID == 0 ]]; then
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
543 pfind() { #find *$1* in $PATH
544 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
546 IFS=: pathArray=($PATH); unset IFS
547 find "${pathArray[@]}" -iname "*$1*"
551 pwd() { # do pwd + some other info.
552 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
556 pwgen() { # generate a random password, with digits & punctuation and without
558 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
560 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
564 q() { # start / launch a program in the backround and redir output to null
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 "$@"; }
588 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
593 complete -F _root_command s sb
595 # use -ll, less secure but faster.
600 # sudo redo. be aware, this command may not work right on strange distros or earlier software
602 if [[ $# == 0 ]]; then
603 sudo -E bash -c -l "$(history -p '!!')"
605 echo this command redos last history item. no argument is accepted
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
615 local logdir do_stamp arg_base
616 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
619 while getopts "lt" option
622 l ) arg_base=$logdir ;;
626 shift $(($OPTIND - 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
632 splay() { # script replay
633 #logRoot="$HOME/typescripts/"
634 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
635 scriptreplay "$1.t" "$1.s"
642 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
646 ts() { # start editing a new file
647 [[ $# != 1 ]] && echo "I need a filename." && return 1
649 if [[ $- != *i* ]]; then
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"
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
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"
672 echo "#!/bin/bash" > "$1"
675 [[ $quiet ]] || g "$1"
679 tx() { # toggle set -x, and the prompt so it doesn't spam
680 if [[ $- == *x* ]]; then
682 PROMPT_COMMAND=prompt_command
693 if [[ $OS == Windows_NT ]]; then
704 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
709 if type gvfs-open &> /dev/null ; then
714 # another alternative is run-mailcap
720 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
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"
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
745 # commands to run when bash exits normally
749 # temporary variables to test colorization
750 # some copied from gentoo /etc/bash/bashrc,
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
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
766 if ${use_color} && [[ $- == *i* ]]; then
768 if [[ $XTERM_VERSION == Cygwin* ]]; then
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' ;;
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
807 # Try to keep environment pollution down, EPA loves us.
808 unset safe_term match_lhs use_color
820 if [[ $- == *i* ]]; then
821 # git branch/status prompt function
822 if [[ $OS != Windows_NT ]]; then
823 GIT_PS1_SHOWDIRTYSTATE=true
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
830 # in case we didn't source git-prompt.sh
831 if ! declare -f __git_ps1 > /dev/null; then
837 # this needs to come before next ps1 stuff
838 if [[ $BASH_VERSION == [456789]* ]]; then
843 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
845 bind -m vi-command B:shell-backward-word
846 bind -m vi-command W:shell-forward-word
852 if [[ $SSH_CLIENT ]]; then
857 local return=$? # this MUST COME FIRST
859 local ps_char ps_color
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;"
868 local title_escape="\033]0;"
870 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
874 0) ps_color="$(get_term_color blue)"
877 1) ps_color="$(get_term_color green)"
880 *) ps_color="$(get_term_color yellow)"
884 if [[ ! -O . ]]; then # not owner
885 if [[ -w . ]]; then # writable
886 ps_color="$(get_term_color bold red)"
888 ps_color="$(get_term_color bold green)"
891 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
893 PROMPT_COMMAND=prompt_command
897 ###########################################
898 # stuff that makes sense to be at the end #
899 ###########################################
900 if [[ "$SUDOD" ]]; then
902 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
911 # if someone exported $SOE, catch errors