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 #####################
200 command grep --binary-files=without-match --color=auto "$@"
214 calc() { echo "scale=3; $*" | bc -l; }
217 if [[ $1 == .. ]]; then
218 echo 'be cool, use the alias ".." instead :)'
224 # makes it so chown -R symlink affects the symlink and its target.
226 if [[ $1 == -R ]]; then
228 command chown -h "$@"
230 command chown -RH "$@"
240 if [[ $# == 0 ]]; then
241 cp /a/bin/data/COPYING .
243 cp /a/bin/data/COPYING "$@"
249 diff --strip-trailing-cr -w "$@" # diff content
254 if [[ -f /etc/fedora-release ]]; then
257 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
263 date "+%A, %B %d, %rq" "$@"
270 envload() { # load environment from a previous: export > file
271 local file=${1:-$HOME/.${USER}_env}
272 eval "$(export | sed 's/^declare -x/export -n/')"
273 while IFS= read -r line; do
274 # declare -x makes variables local to a function
275 eval ${line/#declare -x/export}
281 # havn't tested these:
282 #file cut copy and paste, like the text buffers :)
283 _fbufferinit() { # internal use by
284 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
285 rm -rf "$my_f_tempdir"/*
289 cp "$@" "$my_f_tempdir"/
293 mv "$@" "$my_f_tempdir"/
295 fpst() { # file paste
296 [[ $2 ]] && { echo too many arguments; return 1; }
298 cp "$my_f_tempdir"/* "$target"
302 # find array. make an array of file names found by find into $x
303 # argument: find arguments
304 # return: find results in an array $x
306 while read -rd ''; do
308 done < <(find "$@" -print0);
312 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
313 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
315 gitroot || return 1 # function to set gitroot
317 git symbolic-ref HEAD refs/heads/$1
323 firefox -P default "$@" >/dev/null 2>&1
327 firefox -P alt "$@" >/dev/null 2>&1
334 # horizontal row. used to break up output
335 hr() { printf "$(tput setaf 5)█$(tput sgr0)%.0s" $(seq $COLUMNS); }
341 # modified from ~/local/bin/git-completion.bash
342 # other completion commands are mostly taken from bash_completion package
343 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
344 || complete -o default -o nospace -F _git i
349 find . -iname '*'"$*"'*'
355 if [[ $PWD == /[iap] ]]; then
356 command ls -A --color=auto -I lost+found "$@"
358 command ls -A --color=auto "$@"
363 lld() { ll -d "$@"; }
366 low() { # make filenames all lowercase
369 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
370 [[ $y != $x ]] && mv "$x" "$y"
375 lower() { # make first letter of filenames lowercase.
378 if [[ ${x::1} == [A-Z] ]]; then
379 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
380 safe_rename "$x" "$y"
386 if [[ $# != 2 ]]; then
387 echo safe_rename error: $# args, need 2 >2
389 elif [[ $1 != $2 ]]; then
391 echo Cannot rename "$1" to "$2" as it already exists.
402 safe_rename "$x" "$y"
406 # force symbolic link creation.
407 # trash-put any existing targets,
408 # then send all arguments to ln -s
410 if [[ $# -gt 1 && -d ${!#} ]]; then
413 for x in "${@:1:$(($#-1))}"; do # all but last arg
414 # a broken symlink will fail the "exists" -e test
415 [[ -e "${x##*/}" || -L "${x##*/}" ]] && trash-put "${x##*/}"
418 elif [[ $# -eq 2 ]]; then
419 [[ -e "$2" || -L "$2" ]] && rm "$2"
421 [[ -e "${1##*/}" || -L "${1##*/}" ]] && rm "${1##*/}"
429 # aliases would be much more compact, but they can't be used as ssh commands
430 # also, to be used in a script, you need -i which prints annoying
431 # warnings. instead, use -l in a script to source this file
432 if type -p yum > /dev/null; then
434 if [[ $EUID == 0 ]]; then
441 if [[ $EUID == 0 ]]; then
444 sudo yum -y install "$@"
448 if [[ $EUID == 0 ]]; then
456 if [[ $EUID == 0 ]]; then
463 if [[ $EUID == 0 ]]; then
464 aptitude -y install "$@"
466 sudo aptitude -y install "$@"
470 if [[ $EUID == 0 ]]; then
473 sudo aptitude search "$@"
482 # fix root file ownership for FILE argument.
483 # check if parent or grandparent is not root and if the dir of FILE is also
484 # owned by that user, and change ownership to that user
487 if [[ $EUID == 0 ]]; then
488 [[ -e $1 ]] || touch $1
489 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
491 argdir=$(dirstrip "$1")
492 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
493 if ! chown "--reference=$argdir" "$1"; then
494 echo failed to fix bad ownership file permissons
502 pfind() { #find *$1* in $PATH
503 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
505 IFS=: pathArray=($PATH); unset IFS
506 find "${pathArray[@]}" -iname "*$1*"
515 pwd() { # do pwd + some other info.
516 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
520 pwgen() { # generate a random password, with digits & punctuation and without
522 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
524 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
528 q() { # start / launch a program in the backround and redir output to null
538 # rsync, root is required to keep permissions right.
539 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
540 # --no-times --delete
541 # basically, make an exact copy, use checksums instead of file times to be more accurate
542 rl() { rsync -ahvic --delete "$@"; }
543 # don't delete files on the target end which do not exist on the original end:
544 rld() { rsync -ahvic "$@"; }
545 complete -F _rsync -o nospace rld rlt fl
546 # rl without preserving modification time. for some reason I had this as default before.
547 # perhaps that reason will come up again and I will document it.
548 rlt() { rsync -ahvic --delete --no-t "$@"; }
552 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
557 complete -F _root_command s sb
559 # use -ll, less secure but faster.
564 # sudo redo. be aware, this command may not work right on strange distros or earlier software
566 if [[ $# == 0 ]]; then
567 sudo -E bash -c -l "$(history -p '!!')"
569 echo this command redos last history item. no argument is accepted
575 # log with script. timing is $1.t and script is $1.s
576 # -l to save to ~/typescripts/
577 # -t to add a timestamp to the filenames
579 local logdir do_stamp arg_base
580 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
583 while getopts "lt" option
586 l ) arg_base=$logdir ;;
590 shift $(($OPTIND - 1))
592 [[ -e $logdir ]] || mkdir -p $logdir
593 $do_stamp && arg_base+=$(date +%F.%T%z)
594 script -t $arg_base.s 2> $arg_base.t
596 splay() { # script replay
597 #logRoot="$HOME/typescripts/"
598 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
599 scriptreplay "$1.t" "$1.s"
606 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
610 ts() { # start editing a new file
611 [[ $# != 1 ]] && echo "I need a filename." && return 1
613 if [[ $- != *i* ]]; then
616 if [[ $1 == *.c ]]; then
617 e '#include <stdio.h>' >"$1"
618 e '#include <stdlib.h>' >>"$1"
619 e 'int main(int argc, char * argv[]) {' >>"$1"
620 e ' printf( "hello world\n");' >>"$1"
621 e ' return 0;' >>"$1"
623 e "${1%.c}: $1" > Makefile
624 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
625 e "#!/bin/bash" >run.sh
626 e "./${1%.c}" >>run.sh
628 elif [[ $1 == *.java ]]; then
629 e "public class ${1%.*} {" >"$1"
630 e ' public static void main(String[] args) {' >>"$1"
631 e ' System.out.println("Hello, world!");' >>"$1"
636 echo "#!/bin/bash" > "$1"
639 [[ $quiet ]] || g "$1"
643 tx() { # toggle set -x
644 if [[ $- == *x* ]]; then
654 if [[ $OS == Windows_NT ]]; then
665 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
670 if type gvfs-open &> /dev/null ; then
675 # another alternative is run-mailcap
681 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
686 hl() { # history limit. Write extra history to archive file.
687 local max_lines linecount tempfile
688 if ! [[ -w $HISTFILE ]] || ! [[ -w ${HISTFILE}_archive ]]; then
689 echo "error: a history file is not writable."
694 max_lines=$(($1 * 2)) # 2 lines for every history command
698 linecount=$(wc -l < $HISTFILE)
699 linecount=${linecount:-0}
700 if (($linecount > $max_lines)); then
701 prune_lines=$(($linecount - $max_lines))
703 [[ $tempfile ]] || { echo mktemp failed; return 1; }
704 head -$prune_lines $HISTFILE >> ${HISTFILE}a \
705 && sed -e "1,${prune_lines}d" $HISTFILE > $tempfile \
706 && mv $tempfile $HISTFILE
709 perm_fix ${HISTFILE}_archive
714 # run hl when bash exits normally
719 # temporary variables to test colorization
720 # some copied from gentoo /etc/bash/bashrc,
722 # dircolors --print-database uses its own built-in database
723 # instead of using /etc/DIR_COLORS. Try to use the external file
724 # first to take advantage of user additions.
725 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
727 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
728 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
729 [[ -z ${match_lhs} ]] \
730 && type -P dircolors >/dev/null \
731 && match_lhs=$(dircolors --print-database)
732 # test if our $TERM is in the TERM values in dircolor
733 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
736 if ${use_color} && [[ $- == *i* ]]; then
738 if [[ $XTERM_VERSION == Cygwin* ]]; then
742 underl) echo -n $'\E[4m' ;;
743 bold) echo -n $'\E[1m' ;;
744 red) echo -n $'\E[31m' ;;
745 green) echo -n $'\E[32m' ;;
746 blue) echo -n $'\E[34m' ;;
747 cyan) echo -n $'\E[36m' ;;
748 yellow) echo -n $'\E[33m' ;;
749 purple) echo -n $'\E[35m' ;;
750 nocolor) echo -n $'\E(B\E[m' ;;
759 underl) echo -n $(tput smul) ;;
760 bold) echo -n $(tput bold) ;;
761 red) echo -n $(tput setaf 1) ;;
762 green) echo -n $(tput setaf 2) ;;
763 blue) echo -n $(tput setaf 4) ;;
764 cyan) echo -n $(tput setaf 6) ;;
765 yellow) echo -n $(tput setaf 3) ;;
766 purple) echo -n $(tput setaf 5) ;;
767 nocolor) echo -n $(tput sgr0) ;; # no font attributes
777 # Try to keep environment pollution down, EPA loves us.
778 unset safe_term match_lhs use_color
790 if [[ $- == *i* ]]; then
791 # git branch/status prompt function
792 if [[ $OS != Windows_NT ]]; then
793 GIT_PS1_SHOWDIRTYSTATE=true
795 # arch source location
796 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
797 # fedora/debian source
798 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
800 # in case we didn't source git-prompt.sh
801 if ! declare -f __git_ps1 > /dev/null; then
807 # this needs to come before next ps1 stuff
808 if [[ $BASH_VERSION == [456789]* ]]; then
813 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
815 bind -m vi-command B:shell-backward-word
816 bind -m vi-command W:shell-forward-word
822 if [[ $SSH_CLIENT ]]; then
827 local return=$? # this MUST COME FIRST
829 local ps_char ps_color
831 history -a # save history
832 history -n # read any new history
833 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
834 # from the screen man page
835 if [[ $TERM == screen* ]]; then
836 local title_escape="\033]..2;"
838 local title_escape="\033]0;"
840 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
844 0) ps_color="$(get_term_color blue)"
847 1) ps_color="$(get_term_color green)"
850 *) ps_color="$(get_term_color yellow)"
854 if [[ ! -O . ]]; then # not owner
855 if [[ -w . ]]; then # writable
856 ps_color="$(get_term_color bold red)"
858 ps_color="$(get_term_color bold green)"
861 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
863 PROMPT_COMMAND=prompt_command
867 ###########################################
868 # stuff that makes sense to be at the end #
869 ###########################################
870 if [[ "$SUDOD" ]]; then
872 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
881 # if someone exported $SOE, catch errors