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'
88 stty werase undef lnext undef stop undef start undef
89 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
90 # gnome-terminal, overridden by bash, or disabled by the system
92 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
93 if [[ $TERM == "xterm" ]]; then
94 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
95 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
97 bind '"\eOc": shell-forward-word'
98 bind '"\eOd": shell-backward-word'
105 # history number. History expansion is good.
107 # history file size limit, set to unlimited.
109 # max commands 1 session can append to history
111 # this needs to be different from the derault because
112 # default HISTFILESIZE is 500 and could clobber our history
114 HISTTIMEFORMAT="%I:%M %p %m/%d "
115 # duplicate, single letter, and space prepended commands do not go in history
118 export BC_LINE_LENGTH=0
120 path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
121 path_add $HOME/bin/bash-programs-by-ian/utils
122 # note, if I use a machine I don't want files readable by all users, set
123 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
134 if [[ $- == *i* ]]; then
139 # remove any default aliases for these
140 alias ls > /dev/null 2>&1 && unalias ls
141 alias ll > /dev/null 2>&1 && unalias ll
142 alias grep > /dev/null 2>&1 && unalias grep
146 command mkdir -p "$@"
151 complete -A stopped -P '"%' -S '"' d
156 # note: gksudo is recommended for X apps because it does not set the
157 # home directory to the same.
159 if [[ $- == *i* ]]; then
160 # extra space at the end allows aliases to work
161 alias s='SUDOD="$PWD" sudo -i '
164 if [[ $EUID != 0 || $1 == -* ]]; then
175 if [[ $OS == Windows_NT ]]; then
176 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
178 alias j='command cygpath'
179 alias t='command cygstart'
180 alias cygstart='echo be quick, use the alias "t" instead :\)'
181 alias cygpath='echo be quick, use the alias "j" instead :\)'
186 #####################
188 #####################
204 grep -i --binary-files=without-match --color=auto "$@"
208 grep -ri --binary-files=without-match --color=auto "$@"
216 calc() { echo "scale=3; $*" | bc -l; }
219 if [[ $1 == .. ]]; then
220 echo 'be cool, use the alias ".." instead :)'
226 # makes it so chown -R symlink affects the symlink and its target.
228 if [[ $1 == -R ]]; then
230 command chown -h "$@"
232 command chown -RH "$@"
242 if [[ $# == 0 ]]; then
243 cp /a/bin/data/COPYING .
245 cp /a/bin/data/COPYING "$@"
251 diff --strip-trailing-cr -w "$@" # diff content
256 if [[ -f /etc/fedora-release ]]; then
259 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
265 date "+%A, %B %d, %r" "$@"
272 envload() { # load environment from a previous: export > file
273 local file=${1:-$HOME/.${USER}_env}
274 eval "$(export | sed 's/^declare -x/export -n/')"
275 while IFS= read -r line; do
276 # declare -x makes variables local to a function
277 eval ${line/#declare -x/export}
283 # havn't tested these:
284 #file cut copy and paste, like the text buffers :)
285 _fbufferinit() { # internal use by
286 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
287 rm -rf "$my_f_tempdir"/*
291 cp "$@" "$my_f_tempdir"/
295 mv "$@" "$my_f_tempdir"/
297 fpst() { # file paste
298 [[ $2 ]] && { echo too many arguments; return 1; }
300 cp "$my_f_tempdir"/* "$target"
304 # find array. make an array of file names found by find into $x
305 # argument: find arguments
306 # return: find results in an array $x
308 while read -rd ''; do
310 done < <(find "$@" -print0);
314 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
315 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
317 gitroot || return 1 # function to set gitroot
319 git symbolic-ref HEAD refs/heads/$1
325 firefox -P default "$@" >/dev/null 2>&1
329 firefox -P alt "$@" >/dev/null 2>&1
336 # horizontal row. used to break up output
337 hr() { printf "$(tput setaf 5)█$(tput sgr0)%.0s" $(seq $COLUMNS); }
343 # modified from ~/local/bin/git-completion.bash
344 # other completion commands are mostly taken from bash_completion package
345 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
346 || complete -o default -o nospace -F _git i
351 find . -iname '*'"$*"'*'
357 if [[ $PWD == /[iap] ]]; then
358 command ls -A --color=auto -I lost+found "$@"
360 command ls -A --color=auto "$@"
365 lld() { ll -d "$@"; }
368 low() { # make filenames all lowercase
371 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
372 [[ $y != $x ]] && mv "$x" "$y"
377 lower() { # make first letter of filenames lowercase.
380 if [[ ${x::1} == [A-Z] ]]; then
381 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
382 safe_rename "$x" "$y"
388 if [[ $# != 2 ]]; then
389 echo safe_rename error: $# args, need 2 >2
391 elif [[ $1 != $2 ]]; then
393 echo Cannot rename "$1" to "$2" as it already exists.
404 safe_rename "$x" "$y"
408 # force symbolic link creation.
409 # trash-put any existing files where links would be created.
410 # mkdir -p the directory containing the link(s) if needed.
411 # then do ln -s -- "$@"
413 if [[ $# -gt 2 && ! -d ${!#} ]]; then
416 if [[ $# -gt 1 && -d ${!#} ]]; then
419 for x in "${@:1:$(($#-1))}"; do # all but last arg
420 # remove any trailing slashes
422 # remove any leading directory components
424 te "$x" && trash-put "$x"
427 elif [[ $# -eq 2 ]]; then
430 elif [[ ! -d $(getdir "$2") ]]; then
431 mkdir -p $(getdir "$2")
434 te "${1##*/}" && rm "${1##*/}"
442 # aliases would be much more compact, but they can't be used as ssh commands
443 # also, to be used in a script, you need -i which prints annoying
444 # warnings. instead, use -l in a script to source this file
445 if type -p yum > /dev/null; then
447 if [[ $EUID == 0 ]]; then
454 if [[ $EUID == 0 ]]; then
457 sudo yum -y install "$@"
461 if [[ $EUID == 0 ]]; then
469 if [[ $EUID == 0 ]]; then
476 if [[ $EUID == 0 ]]; then
477 aptitude -y install "$@"
479 sudo aptitude -y install "$@"
483 if [[ $EUID == 0 ]]; then
486 sudo aptitude search "$@"
496 [[ -e "$x" || -L "$x" ]] || ret=1
502 # fix root file ownership for FILE argument.
503 # check if parent or grandparent is not root and if the dir of FILE is also
504 # owned by that user, and change ownership to that user
507 if [[ $EUID == 0 ]]; then
508 [[ -e $1 ]] || touch $1
509 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
511 argdir=$(getdir "$1")
512 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
513 if ! chown "--reference=$argdir" "$1"; then
514 echo failed to fix bad ownership file permissons
522 pfind() { #find *$1* in $PATH
523 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
525 IFS=: pathArray=($PATH); unset IFS
526 find "${pathArray[@]}" -iname "*$1*"
530 pwd() { # do pwd + some other info.
531 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
535 pwgen() { # generate a random password, with digits & punctuation and without
537 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
539 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
543 q() { # start / launch a program in the backround and redir output to null
553 # rsync, root is required to keep permissions right.
554 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
555 # --no-times --delete
556 # basically, make an exact copy, use checksums instead of file times to be more accurate
557 rl() { rsync -ahvic --delete "$@"; }
558 # don't delete files on the target end which do not exist on the original end:
559 rld() { rsync -ahvic "$@"; }
560 complete -F _rsync -o nospace rld rlt fl
561 # rl without preserving modification time. for some reason I had this as default before.
562 # perhaps that reason will come up again and I will document it.
563 rlt() { rsync -ahvic --delete --no-t "$@"; }
567 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
572 complete -F _root_command s sb
574 # use -ll, less secure but faster.
579 # sudo redo. be aware, this command may not work right on strange distros or earlier software
581 if [[ $# == 0 ]]; then
582 sudo -E bash -c -l "$(history -p '!!')"
584 echo this command redos last history item. no argument is accepted
590 # log with script. timing is $1.t and script is $1.s
591 # -l to save to ~/typescripts/
592 # -t to add a timestamp to the filenames
594 local logdir do_stamp arg_base
595 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
598 while getopts "lt" option
601 l ) arg_base=$logdir ;;
605 shift $(($OPTIND - 1))
607 [[ -e $logdir ]] || mkdir -p $logdir
608 $do_stamp && arg_base+=$(date +%F.%T%z)
609 script -t $arg_base.s 2> $arg_base.t
611 splay() { # script replay
612 #logRoot="$HOME/typescripts/"
613 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
614 scriptreplay "$1.t" "$1.s"
621 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
625 ts() { # start editing a new file
626 [[ $# != 1 ]] && echo "I need a filename." && return 1
628 if [[ $- != *i* ]]; then
631 if [[ $1 == *.c ]]; then
632 e '#include <stdio.h>' >"$1"
633 e '#include <stdlib.h>' >>"$1"
634 e 'int main(int argc, char * argv[]) {' >>"$1"
635 e ' printf( "hello world\n");' >>"$1"
636 e ' return 0;' >>"$1"
638 e "${1%.c}: $1" > Makefile
639 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
640 e "#!/bin/bash" >run.sh
641 e "./${1%.c}" >>run.sh
643 elif [[ $1 == *.java ]]; then
644 e "public class ${1%.*} {" >"$1"
645 e ' public static void main(String[] args) {' >>"$1"
646 e ' System.out.println("Hello, world!");' >>"$1"
651 echo "#!/bin/bash" > "$1"
654 [[ $quiet ]] || g "$1"
658 tx() { # toggle set -x, and the prompt so it doesn't spam
659 if [[ $- == *x* ]]; then
661 PROMPT_COMMAND=prompt_command
672 if [[ $OS == Windows_NT ]]; then
683 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
688 if type gvfs-open &> /dev/null ; then
693 # another alternative is run-mailcap
699 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
703 hl() { # history limit. Write extra history to archive file.
704 local max_lines linecount tempfile
705 for x in $HISTFILE ${HISTFILE}_archive; do
706 if [[ -e $x && ! -w $x ]]; then
707 echo "error: history file $x is not writable."
713 max_lines=$(($1 * 2)) # 2 lines for every history command
717 linecount=$(wc -l < $HISTFILE)
718 linecount=${linecount:-0}
719 if (($linecount > $max_lines)); then
720 prune_lines=$(($linecount - $max_lines))
722 [[ $tempfile ]] || { echo mktemp failed; return 1; }
723 head -$prune_lines $HISTFILE >> ${HISTFILE}a \
724 && sed -e "1,${prune_lines}d" $HISTFILE > $tempfile \
725 && mv $tempfile $HISTFILE
728 perm_fix ${HISTFILE}_archive
733 # commands to run when bash exits normally
737 # temporary variables to test colorization
738 # some copied from gentoo /etc/bash/bashrc,
740 # dircolors --print-database uses its own built-in database
741 # instead of using /etc/DIR_COLORS. Try to use the external file
742 # first to take advantage of user additions.
743 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
745 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
746 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
747 [[ -z ${match_lhs} ]] \
748 && type -P dircolors >/dev/null \
749 && match_lhs=$(dircolors --print-database)
750 # test if our $TERM is in the TERM values in dircolor
751 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
754 if ${use_color} && [[ $- == *i* ]]; then
756 if [[ $XTERM_VERSION == Cygwin* ]]; then
760 underl) echo -n $'\E[4m' ;;
761 bold) echo -n $'\E[1m' ;;
762 red) echo -n $'\E[31m' ;;
763 green) echo -n $'\E[32m' ;;
764 blue) echo -n $'\E[34m' ;;
765 cyan) echo -n $'\E[36m' ;;
766 yellow) echo -n $'\E[33m' ;;
767 purple) echo -n $'\E[35m' ;;
768 nocolor) echo -n $'\E(B\E[m' ;;
777 underl) echo -n $(tput smul) ;;
778 bold) echo -n $(tput bold) ;;
779 red) echo -n $(tput setaf 1) ;;
780 green) echo -n $(tput setaf 2) ;;
781 blue) echo -n $(tput setaf 4) ;;
782 cyan) echo -n $(tput setaf 6) ;;
783 yellow) echo -n $(tput setaf 3) ;;
784 purple) echo -n $(tput setaf 5) ;;
785 nocolor) echo -n $(tput sgr0) ;; # no font attributes
795 # Try to keep environment pollution down, EPA loves us.
796 unset safe_term match_lhs use_color
808 if [[ $- == *i* ]]; then
809 # git branch/status prompt function
810 if [[ $OS != Windows_NT ]]; then
811 GIT_PS1_SHOWDIRTYSTATE=true
813 # arch source location
814 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
815 # fedora/debian source
816 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
818 # in case we didn't source git-prompt.sh
819 if ! declare -f __git_ps1 > /dev/null; then
825 # this needs to come before next ps1 stuff
826 if [[ $BASH_VERSION == [456789]* ]]; then
831 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
833 bind -m vi-command B:shell-backward-word
834 bind -m vi-command W:shell-forward-word
840 if [[ $SSH_CLIENT ]]; then
845 local return=$? # this MUST COME FIRST
847 local ps_char ps_color
849 history -a # save history
850 history -n # read any new history
851 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
852 # from the screen man page
853 if [[ $TERM == screen* ]]; then
854 local title_escape="\033]..2;"
856 local title_escape="\033]0;"
858 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
862 0) ps_color="$(get_term_color blue)"
865 1) ps_color="$(get_term_color green)"
868 *) ps_color="$(get_term_color yellow)"
872 if [[ ! -O . ]]; then # not owner
873 if [[ -w . ]]; then # writable
874 ps_color="$(get_term_color bold red)"
876 ps_color="$(get_term_color bold green)"
879 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
881 PROMPT_COMMAND=prompt_command
885 ###########################################
886 # stuff that makes sense to be at the end #
887 ###########################################
888 if [[ "$SUDOD" ]]; then
890 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
899 # if someone exported $SOE, catch errors