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 # so I can share my bashrc
33 source $HOME/bin/bash_private
34 source $HOME/path_add-function
45 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
47 #use extra globing features. See man bash, search extglob.
49 #include .files when globbing.
52 # disabled because it is broken with bash_completion package. It is a known bug they hope to fix.
53 # When a glob expands to nothing, make it an empty string instead of the literal characters.
56 # make tab on an empty line do nothing
57 shopt -s no_empty_cmd_completion
61 # http://bash-completion.alioth.debian.org/
62 # i was using the git version for a while. not bothering now.
63 # seems a bit inefficient to source it here, and let the system bash
64 # scripts source it too. todo, investigate if I am super bored sometime
65 if [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
66 . /usr/share/bash-completion/bash_completion
69 # fix spelling errors for cd, only in interactive shell
71 # append history instead of overwritting it
73 # for compatibility, per gentoo/debian bashrc
75 # attempt to save multiline single commands as single history entries.
78 if [[ $- == *i* ]]; then
79 # for readline-complete.el
80 if [[ $INSIDE_EMACS ]]; then
81 bind 'set horizontal-scroll-mode on'
82 bind 'set print-completions-horizontally on'
85 stty werase undef lnext undef stop undef start undef
86 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
87 # gnome-terminal, overridden by bash, or disabled by the system
89 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
90 if [[ $TERM == "xterm" ]]; then
91 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
92 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
94 bind '"\eOc": shell-forward-word'
95 bind '"\eOd": shell-backward-word'
102 # history number. History expansion is good.
104 # history file size limit, set to unlimited.
106 # max commands 1 session can append to history
108 # this needs to be different from the derault because
109 # default HISTFILESIZE is 500 and could clobber our history
111 HISTTIMEFORMAT="%I:%M %p %m/%d "
112 # duplicate, single letter, and space prepended commands do not go in history
115 export BC_LINE_LENGTH=0
117 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
118 path_add $HOME/bin/bash-programs-by-ian/utils
119 # note, if I use a machine I don't want files readable by all users, set
120 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
131 if [[ $- == *i* ]]; then
136 # remove any default aliases for these
137 alias ls > /dev/null 2>&1 && unalias ls
138 alias ll > /dev/null 2>&1 && unalias ll
139 alias grep > /dev/null 2>&1 && unalias grep
143 command mkdir -p "$@"
148 complete -A stopped -P '"%' -S '"' d
153 # note: gksudo is recommended for X apps because it does not set the
154 # home directory to the same.
156 if [[ $- == *i* ]]; then
157 # extra space at the end allows aliases to work
158 alias s='SUDOD="$PWD" sudo -i '
161 if [[ $EUID != 0 || $1 == -* ]]; then
172 if [[ $OS == Windows_NT ]]; then
173 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
175 alias j='command cygpath'
176 alias t='command cygstart'
177 alias cygstart='echo be quick, use the alias "t" instead :\)'
178 alias cygpath='echo be quick, use the alias "j" instead :\)'
183 #####################
185 #####################
201 grep -i --binary-files=without-match --color=auto "$@"
213 calc() { echo "scale=3; $*" | bc -l; }
216 if [[ $1 == .. ]]; then
217 echo 'be cool, use the alias ".." instead :)'
223 # makes it so chown -R symlink affects the symlink and its target.
225 if [[ $1 == -R ]]; then
227 command chown -h "$@"
229 command chown -RH "$@"
239 if [[ $# == 0 ]]; then
240 cp /a/bin/data/COPYING .
242 cp /a/bin/data/COPYING "$@"
248 diff --strip-trailing-cr -w "$@" # diff content
253 if [[ -f /etc/fedora-release ]]; then
256 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
262 date "+%A, %B %d, %r" "$@"
269 envload() { # load environment from a previous: export > file
270 local file=${1:-$HOME/.${USER}_env}
271 eval "$(export | sed 's/^declare -x/export -n/')"
272 while IFS= read -r line; do
273 # declare -x makes variables local to a function
274 eval ${line/#declare -x/export}
280 # havn't tested these:
281 #file cut copy and paste, like the text buffers :)
282 _fbufferinit() { # internal use by
283 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
284 rm -rf "$my_f_tempdir"/*
288 cp "$@" "$my_f_tempdir"/
292 mv "$@" "$my_f_tempdir"/
294 fpst() { # file paste
295 [[ $2 ]] && { echo too many arguments; return 1; }
297 cp "$my_f_tempdir"/* "$target"
301 # find array. make an array of file names found by find into $x
302 # argument: find arguments
303 # return: find results in an array $x
305 while read -rd ''; do
307 done < <(find "$@" -print0);
311 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
312 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
314 gitroot || return 1 # function to set gitroot
316 git symbolic-ref HEAD refs/heads/$1
322 firefox -P default "$@" >/dev/null 2>&1
326 firefox -P alt "$@" >/dev/null 2>&1
333 # horizontal row. used to break up output
334 hr() { printf "$(tput setaf 5)█$(tput sgr0)%.0s" $(seq $COLUMNS); }
340 # modified from ~/local/bin/git-completion.bash
341 # other completion commands are mostly taken from bash_completion package
342 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
343 || complete -o default -o nospace -F _git i
348 find . -iname '*'"$*"'*'
354 if [[ $PWD == /[iap] ]]; then
355 command ls -A --color=auto -I lost+found "$@"
357 command ls -A --color=auto "$@"
362 lld() { ll -d "$@"; }
365 low() { # make filenames all lowercase
368 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
369 [[ $y != $x ]] && mv "$x" "$y"
374 lower() { # make first letter of filenames lowercase.
377 if [[ ${x::1} == [A-Z] ]]; then
378 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
379 safe_rename "$x" "$y"
385 if [[ $# != 2 ]]; then
386 echo safe_rename error: $# args, need 2 >2
388 elif [[ $1 != $2 ]]; then
390 echo Cannot rename "$1" to "$2" as it already exists.
401 safe_rename "$x" "$y"
405 # force symbolic link creation.
406 # trash-put any existing targets,
407 # then send all arguments to ln -s
409 if [[ $# -gt 1 && -d ${!#} ]]; then
412 for x in "${@:1:$(($#-1))}"; do # all but last arg
413 # a broken symlink will fail the "exists" -e test
414 [[ -e "${x##*/}" || -L "${x##*/}" ]] && trash-put "${x##*/}"
417 elif [[ $# -eq 2 ]]; then
418 [[ -e "$2" || -L "$2" ]] && rm "$2"
420 [[ -e "${1##*/}" || -L "${1##*/}" ]] && rm "${1##*/}"
428 # aliases would be much more compact, but they can't be used as ssh commands
429 # also, to be used in a script, you need -i which prints annoying
430 # warnings. instead, use -l in a script to source this file
431 if type -p yum > /dev/null; then
433 if [[ $EUID == 0 ]]; then
440 if [[ $EUID == 0 ]]; then
443 sudo yum -y install "$@"
447 if [[ $EUID == 0 ]]; then
455 if [[ $EUID == 0 ]]; then
462 if [[ $EUID == 0 ]]; then
463 aptitude -y install "$@"
465 sudo aptitude -y install "$@"
469 if [[ $EUID == 0 ]]; then
472 sudo aptitude search "$@"
481 # fix root file ownership for FILE argument.
482 # check if parent or grandparent is not root and if the dir of FILE is also
483 # owned by that user, and change ownership to that user
486 if [[ $EUID == 0 ]]; then
487 [[ -e $1 ]] || touch $1
488 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
490 argdir=$(dirstrip "$1")
491 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
492 if ! chown "--reference=$argdir" "$1"; then
493 echo failed to fix bad ownership file permissons
501 pfind() { #find *$1* in $PATH
502 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
504 IFS=: pathArray=($PATH); unset IFS
505 find "${pathArray[@]}" -iname "*$1*"
509 pwd() { # do pwd + some other info.
510 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
514 pwgen() { # generate a random password, with digits & punctuation and without
516 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
518 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
522 q() { # start / launch a program in the backround and redir output to null
532 # rsync, root is required to keep permissions right.
533 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
534 # --no-times --delete
535 # basically, make an exact copy, use checksums instead of file times to be more accurate
536 rl() { rsync -ahvic --delete "$@"; }
537 # don't delete files on the target end which do not exist on the original end:
538 rld() { rsync -ahvic "$@"; }
539 complete -F _rsync -o nospace rld rlt fl
540 # rl without preserving modification time. for some reason I had this as default before.
541 # perhaps that reason will come up again and I will document it.
542 rlt() { rsync -ahvic --delete --no-t "$@"; }
546 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
551 complete -F _root_command s sb
553 # use -ll, less secure but faster.
558 # sudo redo. be aware, this command may not work right on strange distros or earlier software
560 if [[ $# == 0 ]]; then
561 sudo -E bash -c -l "$(history -p '!!')"
563 echo this command redos last history item. no argument is accepted
569 # log with script. timing is $1.t and script is $1.s
570 # -l to save to ~/typescripts/
571 # -t to add a timestamp to the filenames
573 local logdir do_stamp arg_base
574 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
577 while getopts "lt" option
580 l ) arg_base=$logdir ;;
584 shift $(($OPTIND - 1))
586 [[ -e $logdir ]] || mkdir -p $logdir
587 $do_stamp && arg_base+=$(date +%F.%T%z)
588 script -t $arg_base.s 2> $arg_base.t
590 splay() { # script replay
591 #logRoot="$HOME/typescripts/"
592 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
593 scriptreplay "$1.t" "$1.s"
600 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
604 ts() { # start editing a new file
605 [[ $# != 1 ]] && echo "I need a filename." && return 1
607 if [[ $- != *i* ]]; then
610 if [[ $1 == *.c ]]; then
611 e '#include <stdio.h>' >"$1"
612 e '#include <stdlib.h>' >>"$1"
613 e 'int main(int argc, char * argv[]) {' >>"$1"
614 e ' printf( "hello world\n");' >>"$1"
615 e ' return 0;' >>"$1"
617 e "${1%.c}: $1" > Makefile
618 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
619 e "#!/bin/bash" >run.sh
620 e "./${1%.c}" >>run.sh
622 elif [[ $1 == *.java ]]; then
623 e "public class ${1%.*} {" >"$1"
624 e ' public static void main(String[] args) {' >>"$1"
625 e ' System.out.println("Hello, world!");' >>"$1"
630 echo "#!/bin/bash" > "$1"
633 [[ $quiet ]] || g "$1"
637 tx() { # toggle set -x, and the prompt so it doesn't spam
638 if [[ $- == *x* ]]; then
640 PROMPT_COMMAND=prompt_command
651 if [[ $OS == Windows_NT ]]; then
662 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
667 if type gvfs-open &> /dev/null ; then
672 # another alternative is run-mailcap
678 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
683 hl() { # history limit. Write extra history to archive file.
684 local max_lines linecount tempfile
685 if ! [[ -w $HISTFILE ]] || ! [[ -w ${HISTFILE}_archive ]]; then
686 echo "error: a history file is not writable."
691 max_lines=$(($1 * 2)) # 2 lines for every history command
695 linecount=$(wc -l < $HISTFILE)
696 linecount=${linecount:-0}
697 if (($linecount > $max_lines)); then
698 prune_lines=$(($linecount - $max_lines))
700 [[ $tempfile ]] || { echo mktemp failed; return 1; }
701 head -$prune_lines $HISTFILE >> ${HISTFILE}a \
702 && sed -e "1,${prune_lines}d" $HISTFILE > $tempfile \
703 && mv $tempfile $HISTFILE
706 perm_fix ${HISTFILE}_archive
710 # run hl when bash exits normally
715 # temporary variables to test colorization
716 # some copied from gentoo /etc/bash/bashrc,
718 # dircolors --print-database uses its own built-in database
719 # instead of using /etc/DIR_COLORS. Try to use the external file
720 # first to take advantage of user additions.
721 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
723 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
724 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
725 [[ -z ${match_lhs} ]] \
726 && type -P dircolors >/dev/null \
727 && match_lhs=$(dircolors --print-database)
728 # test if our $TERM is in the TERM values in dircolor
729 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
732 if ${use_color} && [[ $- == *i* ]]; then
734 if [[ $XTERM_VERSION == Cygwin* ]]; then
738 underl) echo -n $'\E[4m' ;;
739 bold) echo -n $'\E[1m' ;;
740 red) echo -n $'\E[31m' ;;
741 green) echo -n $'\E[32m' ;;
742 blue) echo -n $'\E[34m' ;;
743 cyan) echo -n $'\E[36m' ;;
744 yellow) echo -n $'\E[33m' ;;
745 purple) echo -n $'\E[35m' ;;
746 nocolor) echo -n $'\E(B\E[m' ;;
755 underl) echo -n $(tput smul) ;;
756 bold) echo -n $(tput bold) ;;
757 red) echo -n $(tput setaf 1) ;;
758 green) echo -n $(tput setaf 2) ;;
759 blue) echo -n $(tput setaf 4) ;;
760 cyan) echo -n $(tput setaf 6) ;;
761 yellow) echo -n $(tput setaf 3) ;;
762 purple) echo -n $(tput setaf 5) ;;
763 nocolor) echo -n $(tput sgr0) ;; # no font attributes
773 # Try to keep environment pollution down, EPA loves us.
774 unset safe_term match_lhs use_color
786 if [[ $- == *i* ]]; then
787 # git branch/status prompt function
788 if [[ $OS != Windows_NT ]]; then
789 GIT_PS1_SHOWDIRTYSTATE=true
791 # arch source location
792 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
793 # fedora/debian source
794 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
796 # in case we didn't source git-prompt.sh
797 if ! declare -f __git_ps1 > /dev/null; then
803 # this needs to come before next ps1 stuff
804 if [[ $BASH_VERSION == [456789]* ]]; then
809 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
811 bind -m vi-command B:shell-backward-word
812 bind -m vi-command W:shell-forward-word
818 if [[ $SSH_CLIENT ]]; then
823 local return=$? # this MUST COME FIRST
825 local ps_char ps_color
827 history -a # save history
828 history -n # read any new history
829 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
830 # from the screen man page
831 if [[ $TERM == screen* ]]; then
832 local title_escape="\033]..2;"
834 local title_escape="\033]0;"
836 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
840 0) ps_color="$(get_term_color blue)"
843 1) ps_color="$(get_term_color green)"
846 *) ps_color="$(get_term_color yellow)"
850 if [[ ! -O . ]]; then # not owner
851 if [[ -w . ]]; then # writable
852 ps_color="$(get_term_color bold red)"
854 ps_color="$(get_term_color bold green)"
857 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
859 PROMPT_COMMAND=prompt_command
863 ###########################################
864 # stuff that makes sense to be at the end #
865 ###########################################
866 if [[ "$SUDOD" ]]; then
868 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
877 # if someone exported $SOE, catch errors