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 #use extra globing features. See man bash, search extglob.
59 #include .files when globbing.
61 #but ignore files name . and ..
62 #those are default when this is set to anything, so we just set it to one of them
65 # broken with bash_completion package. Saw a bug for this once. Don't anymore.
66 # still broken in wheezy
67 # still buggered in latest stable from the web, version 2.1
68 # perhaps its fixed in newer git version, which fails to make for me
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
75 # http://bash-completion.alioth.debian.org/
76 # might be sourced by the system already, but I've noticed it not being sourced before
77 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
78 . /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.
93 if [[ $INSIDE_EMACS ]]; then
97 # for readline-complete.el
102 if [[ $- == *i* ]]; then
103 # for readline-complete.el
104 if [[ $INSIDE_EMACS ]]; then
105 bind 'set horizontal-scroll-mode on'
106 bind 'set print-completions-horizontally on'
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 --ifexists /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 # scratch a very annoying itch.
508 # package description width as wide as the screen, and package name field small
509 # aptitude manual can't figure out how wide emacs terminal is,
510 # of course it doesn't consult the $COLUMNS variable...
511 # and in a normal terminal, it makes the package name field ridiculously big
512 # also, remove that useless dash before the description
513 if [[ $EUID == 0 ]]; then
514 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
516 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
522 # test existence / exists
526 [[ -e "$x" || -L "$x" ]] || ret=1
532 # fix root file ownership for FILE argument.
533 # check if parent or grandparent is not root and if the dir of FILE is also
534 # owned by that user, and change ownership to that user
537 if [[ $EUID == 0 ]]; then
539 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
540 argdir=$(getdir "$1")
541 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
542 if ! chown "--reference=$argdir" "$1"; then
543 echo failed to fix bad ownership file permissons
551 pfind() { #find *$1* in $PATH
552 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
554 IFS=: pathArray=($PATH); unset IFS
555 find "${pathArray[@]}" -iname "*$1*"
559 pwd() { # do pwd + some other info.
560 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
564 pwgen() { # generate a random password, with digits & punctuation and without
566 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
568 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
572 q() { # start / launch a program in the backround and redir output to null
579 exit "$@" 2>/dev/null
582 # trash-restore lists everything that has been trashed at or below CWD
583 # This picks out files just in CWD, not subdirectories,
584 # which also match grep $1, usually use $1 for a time string
585 # which you get from running restore-trash once first
589 # last condition is to not ask again for ones we skipped
590 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
591 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
592 name="$(echo "$name" | head -n $nth | tail -n 1 )"
593 read -p "$name [Y/n] " ask
594 if [[ ! $ask || $ask == [Yy] ]]; then
595 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
596 echo $x | restore-trash > /dev/null
597 elif [[ $ask == [Nn] ]]; then
605 # rsync, root is required to keep permissions right.
606 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
607 # --no-times --delete
608 # basically, make an exact copy, use checksums instead of file times to be more accurate
609 rl() { rsync -ahvic --delete "$@"; }
610 # don't delete files on the target end which do not exist on the original end:
611 rld() { rsync -ahvic "$@"; }
612 complete -F _rsync -o nospace rld rlt fl
613 # rl without preserving modification time. for some reason I had this as default before.
614 # perhaps that reason will come up again and I will document it.
615 rlt() { rsync -ahvic --delete --no-t "$@"; }
619 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
624 complete -F _root_command s sb
626 # use -ll, less secure but faster.
631 # sudo redo. be aware, this command may not work right on strange distros or earlier software
633 if [[ $# == 0 ]]; then
634 sudo -E bash -c -l "$(history -p '!!')"
636 echo this command redos last history item. no argument is accepted
642 # log with script. timing is $1.t and script is $1.s
643 # -l to save to ~/typescripts/
644 # -t to add a timestamp to the filenames
646 local logdir do_stamp arg_base
647 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
650 while getopts "lt" option
653 l ) arg_base=$logdir ;;
657 shift $(($OPTIND - 1))
659 [[ -e $logdir ]] || mkdir -p $logdir
660 $do_stamp && arg_base+=$(date +%F.%T%z)
661 script -t $arg_base.s 2> $arg_base.t
663 splay() { # script replay
664 #logRoot="$HOME/typescripts/"
665 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
666 scriptreplay "$1.t" "$1.s"
673 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
677 ts() { # start editing a new file
678 [[ $# != 1 ]] && echo "I need a filename." && return 1
680 if [[ $- != *i* ]]; then
683 if [[ $1 == *.c ]]; then
684 e '#include <stdio.h>' >"$1"
685 e '#include <stdlib.h>' >>"$1"
686 e 'int main(int argc, char * argv[]) {' >>"$1"
687 e ' printf( "hello world\n");' >>"$1"
688 e ' return 0;' >>"$1"
690 e "${1%.c}: $1" > Makefile
691 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
692 e "#!/bin/bash" >run.sh
693 e "./${1%.c}" >>run.sh
695 elif [[ $1 == *.java ]]; then
696 e "public class ${1%.*} {" >"$1"
697 e ' public static void main(String[] args) {' >>"$1"
698 e ' System.out.println("Hello, world!");' >>"$1"
703 echo "#!/bin/bash" > "$1"
706 [[ $quiet ]] || g "$1"
710 tx() { # toggle set -x, and the prompt so it doesn't spam
711 if [[ $- == *x* ]]; then
713 PROMPT_COMMAND=prompt_command
724 if [[ $OS == Windows_NT ]]; then
735 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
740 if type gvfs-open &> /dev/null ; then
745 # another alternative is run-mailcap
751 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
755 hl() { # history limit. Write extra history to archive file.
756 local max_lines linecount tempfile prune_lines
757 local harchive="${HISTFILE}_archive"
758 for x in "$HISTFILE" "$harchive"; do
759 if [[ ! $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
760 echo "error in hl: history file $x no good"
764 history -a # save history
765 max_lines=$HISTFILELINES
766 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
767 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
768 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
769 if (($linecount > $max_lines)); then
770 prune_lines=$(($linecount - $max_lines))
771 head -n $prune_lines "$HISTFILE" >> "$harchive" \
772 && sed -ie "1,${prune_lines}d" $HISTFILE
776 # commands to run when bash exits normally
780 # temporary variables to test colorization
781 # some copied from gentoo /etc/bash/bashrc,
783 # dircolors --print-database uses its own built-in database
784 # instead of using /etc/DIR_COLORS. Try to use the external file
785 # first to take advantage of user additions.
786 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
788 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
789 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
790 [[ -z ${match_lhs} ]] \
791 && type -P dircolors >/dev/null \
792 && match_lhs=$(dircolors --print-database)
793 # test if our $TERM is in the TERM values in dircolor
794 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
797 if ${use_color} && [[ $- == *i* ]]; then
799 if [[ $XTERM_VERSION == Cygwin* ]]; then
803 underl) echo -n $'\E[4m' ;;
804 bold) echo -n $'\E[1m' ;;
805 red) echo -n $'\E[31m' ;;
806 green) echo -n $'\E[32m' ;;
807 blue) echo -n $'\E[34m' ;;
808 cyan) echo -n $'\E[36m' ;;
809 yellow) echo -n $'\E[33m' ;;
810 purple) echo -n $'\E[35m' ;;
811 nocolor) echo -n $'\E(B\E[m' ;;
820 underl) echo -n $(tput smul) ;;
821 bold) echo -n $(tput bold) ;;
822 red) echo -n $(tput setaf 1) ;;
823 green) echo -n $(tput setaf 2) ;;
824 blue) echo -n $(tput setaf 4) ;;
825 cyan) echo -n $(tput setaf 6) ;;
826 yellow) echo -n $(tput setaf 3) ;;
827 purple) echo -n $(tput setaf 5) ;;
828 nocolor) echo -n $(tput sgr0) ;; # no font attributes
838 # Try to keep environment pollution down, EPA loves us.
839 unset safe_term match_lhs use_color
851 if [[ $- == *i* ]]; then
852 # git branch/status prompt function
853 if [[ $OS != Windows_NT ]]; then
854 GIT_PS1_SHOWDIRTYSTATE=true
856 # arch source location
857 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
858 # fedora/debian source
859 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
861 # in case we didn't source git-prompt.sh
862 if ! declare -f __git_ps1 > /dev/null; then
868 # this needs to come before next ps1 stuff
869 if [[ $BASH_VERSION == [456789]* ]]; then
874 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
876 bind -m vi-command B:shell-backward-word
877 bind -m vi-command W:shell-forward-word
883 if [[ $SSH_CLIENT ]]; then
888 local return=$? # this MUST COME FIRST
890 local ps_char ps_color
892 history -a # save history
893 history -n # read any new history
894 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
895 # from the screen man page
896 if [[ $TERM == screen* ]]; then
897 local title_escape="\033]..2;"
899 local title_escape="\033]0;"
901 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
905 0) ps_color="$(get_term_color blue)"
908 1) ps_color="$(get_term_color green)"
909 ps_char="$return \\$"
911 *) ps_color="$(get_term_color yellow)"
912 ps_char="$return \\$"
915 if [[ ! -O . ]]; then # not owner
916 if [[ -w . ]]; then # writable
917 ps_color="$(get_term_color bold red)"
919 ps_color="$(get_term_color bold green)"
922 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
924 PROMPT_COMMAND=prompt_command
928 ###########################################
929 # stuff that makes sense to be at the end #
930 ###########################################
931 if [[ "$SUDOD" ]]; then
933 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
942 # if someone exported $SOE, catch errors