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 if [[ $EUID == 0 ]]; then
510 sudo aptitude search "$@"
516 # test existence / exists
520 [[ -e "$x" || -L "$x" ]] || ret=1
526 # fix root file ownership for FILE argument.
527 # check if parent or grandparent is not root and if the dir of FILE is also
528 # owned by that user, and change ownership to that user
531 if [[ $EUID == 0 ]]; then
533 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
534 argdir=$(getdir "$1")
535 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
536 if ! chown "--reference=$argdir" "$1"; then
537 echo failed to fix bad ownership file permissons
545 pfind() { #find *$1* in $PATH
546 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
548 IFS=: pathArray=($PATH); unset IFS
549 find "${pathArray[@]}" -iname "*$1*"
553 pwd() { # do pwd + some other info.
554 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
558 pwgen() { # generate a random password, with digits & punctuation and without
560 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
562 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
566 q() { # start / launch a program in the backround and redir output to null
576 # rsync, root is required to keep permissions right.
577 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
578 # --no-times --delete
579 # basically, make an exact copy, use checksums instead of file times to be more accurate
580 rl() { rsync -ahvic --delete "$@"; }
581 # don't delete files on the target end which do not exist on the original end:
582 rld() { rsync -ahvic "$@"; }
583 complete -F _rsync -o nospace rld rlt fl
584 # rl without preserving modification time. for some reason I had this as default before.
585 # perhaps that reason will come up again and I will document it.
586 rlt() { rsync -ahvic --delete --no-t "$@"; }
590 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
595 complete -F _root_command s sb
597 # use -ll, less secure but faster.
602 # sudo redo. be aware, this command may not work right on strange distros or earlier software
604 if [[ $# == 0 ]]; then
605 sudo -E bash -c -l "$(history -p '!!')"
607 echo this command redos last history item. no argument is accepted
613 # log with script. timing is $1.t and script is $1.s
614 # -l to save to ~/typescripts/
615 # -t to add a timestamp to the filenames
617 local logdir do_stamp arg_base
618 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
621 while getopts "lt" option
624 l ) arg_base=$logdir ;;
628 shift $(($OPTIND - 1))
630 [[ -e $logdir ]] || mkdir -p $logdir
631 $do_stamp && arg_base+=$(date +%F.%T%z)
632 script -t $arg_base.s 2> $arg_base.t
634 splay() { # script replay
635 #logRoot="$HOME/typescripts/"
636 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
637 scriptreplay "$1.t" "$1.s"
644 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
648 ts() { # start editing a new file
649 [[ $# != 1 ]] && echo "I need a filename." && return 1
651 if [[ $- != *i* ]]; then
654 if [[ $1 == *.c ]]; then
655 e '#include <stdio.h>' >"$1"
656 e '#include <stdlib.h>' >>"$1"
657 e 'int main(int argc, char * argv[]) {' >>"$1"
658 e ' printf( "hello world\n");' >>"$1"
659 e ' return 0;' >>"$1"
661 e "${1%.c}: $1" > Makefile
662 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
663 e "#!/bin/bash" >run.sh
664 e "./${1%.c}" >>run.sh
666 elif [[ $1 == *.java ]]; then
667 e "public class ${1%.*} {" >"$1"
668 e ' public static void main(String[] args) {' >>"$1"
669 e ' System.out.println("Hello, world!");' >>"$1"
674 echo "#!/bin/bash" > "$1"
677 [[ $quiet ]] || g "$1"
681 tx() { # toggle set -x, and the prompt so it doesn't spam
682 if [[ $- == *x* ]]; then
684 PROMPT_COMMAND=prompt_command
695 if [[ $OS == Windows_NT ]]; then
706 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
711 if type gvfs-open &> /dev/null ; then
716 # another alternative is run-mailcap
722 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
726 hl() { # history limit. Write extra history to archive file.
727 local max_lines linecount tempfile prune_lines
728 local harchive="${HISTFILE}_archive"
729 for x in "$HISTFILE" "$harchive"; do
730 if [[ ! $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
731 echo "error in hl: history file $x no good"
735 history -a # save history
736 max_lines=$HISTFILELINES
737 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
738 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
739 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
740 if (($linecount > $max_lines)); then
741 prune_lines=$(($linecount - $max_lines))
742 head -n $prune_lines "$HISTFILE" >> "$harchive" \
743 && sed -ie "1,${prune_lines}d" $HISTFILE
747 # commands to run when bash exits normally
751 # temporary variables to test colorization
752 # some copied from gentoo /etc/bash/bashrc,
754 # dircolors --print-database uses its own built-in database
755 # instead of using /etc/DIR_COLORS. Try to use the external file
756 # first to take advantage of user additions.
757 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
759 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
760 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
761 [[ -z ${match_lhs} ]] \
762 && type -P dircolors >/dev/null \
763 && match_lhs=$(dircolors --print-database)
764 # test if our $TERM is in the TERM values in dircolor
765 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
768 if ${use_color} && [[ $- == *i* ]]; then
770 if [[ $XTERM_VERSION == Cygwin* ]]; then
774 underl) echo -n $'\E[4m' ;;
775 bold) echo -n $'\E[1m' ;;
776 red) echo -n $'\E[31m' ;;
777 green) echo -n $'\E[32m' ;;
778 blue) echo -n $'\E[34m' ;;
779 cyan) echo -n $'\E[36m' ;;
780 yellow) echo -n $'\E[33m' ;;
781 purple) echo -n $'\E[35m' ;;
782 nocolor) echo -n $'\E(B\E[m' ;;
791 underl) echo -n $(tput smul) ;;
792 bold) echo -n $(tput bold) ;;
793 red) echo -n $(tput setaf 1) ;;
794 green) echo -n $(tput setaf 2) ;;
795 blue) echo -n $(tput setaf 4) ;;
796 cyan) echo -n $(tput setaf 6) ;;
797 yellow) echo -n $(tput setaf 3) ;;
798 purple) echo -n $(tput setaf 5) ;;
799 nocolor) echo -n $(tput sgr0) ;; # no font attributes
809 # Try to keep environment pollution down, EPA loves us.
810 unset safe_term match_lhs use_color
822 if [[ $- == *i* ]]; then
823 # git branch/status prompt function
824 if [[ $OS != Windows_NT ]]; then
825 GIT_PS1_SHOWDIRTYSTATE=true
827 # arch source location
828 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
829 # fedora/debian source
830 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
832 # in case we didn't source git-prompt.sh
833 if ! declare -f __git_ps1 > /dev/null; then
839 # this needs to come before next ps1 stuff
840 if [[ $BASH_VERSION == [456789]* ]]; then
845 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
847 bind -m vi-command B:shell-backward-word
848 bind -m vi-command W:shell-forward-word
854 if [[ $SSH_CLIENT ]]; then
859 local return=$? # this MUST COME FIRST
861 local ps_char ps_color
863 history -a # save history
864 history -n # read any new history
865 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
866 # from the screen man page
867 if [[ $TERM == screen* ]]; then
868 local title_escape="\033]..2;"
870 local title_escape="\033]0;"
872 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
876 0) ps_color="$(get_term_color blue)"
879 1) ps_color="$(get_term_color green)"
882 *) ps_color="$(get_term_color yellow)"
886 if [[ ! -O . ]]; then # not owner
887 if [[ -w . ]]; then # writable
888 ps_color="$(get_term_color bold red)"
890 ps_color="$(get_term_color bold green)"
893 PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
895 PROMPT_COMMAND=prompt_command
899 ###########################################
900 # stuff that makes sense to be at the end #
901 ###########################################
902 if [[ "$SUDOD" ]]; then
904 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
913 # if someone exported $SOE, catch errors