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
69 # this note is from 6-2014
72 # make tab on an empty line do nothing
73 shopt -s no_empty_cmd_completion
76 # http://bash-completion.alioth.debian.org/
77 # might be sourced by the system already, but I've noticed it not being sourced before
78 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
79 . /usr/share/bash-completion/bash_completion
83 # fix spelling errors for cd, only in interactive shell
85 # append history instead of overwritting it
87 # for compatibility, per gentoo/debian bashrc
89 # attempt to save multiline single commands as single history entries.
95 if [[ $INSIDE_EMACS ]]; then
99 # for readline-complete.el
104 if [[ $- == *i* ]]; then
105 # for readline-complete.el
106 if [[ $INSIDE_EMACS ]]; then
107 bind 'set horizontal-scroll-mode on'
108 bind 'set print-completions-horizontally on'
109 bind '"\C-i": self-insert'
111 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
112 if [[ $TERM == "xterm" ]]; then
113 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
114 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
116 bind '"\eOc": shell-forward-word'
117 bind '"\eOd": shell-backward-word'
119 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
120 # gnome-terminal, overridden by bash, or disabled by the system
121 stty werase undef lnext undef stop undef start undef
128 # history number. History expansion is good.
130 # history file size limit, set to unlimited.
131 # this needs to be different from the default because
132 # default HISTFILESIZE is 500 and could clobber our history
134 # max commands 1 session can append/read from history
136 # my own history size limit based on lines
137 HISTFILELINES=1000000
139 # the time format display when doing the history command
140 # also, setting this makes the history file record time
141 # of each command as seconds from the epoch
142 HISTTIMEFORMAT="%I:%M %p %m/%d "
143 # consecutive duplicate lines don't go in history
144 HISTCONTROL=ignoredups
145 # just defensively unsetting this
146 # this var can replace HISTCONTROL to do more flexible things like
147 # not saving single char history items or specific names
150 export BC_LINE_LENGTH=0
152 path_add --ifexists /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
153 path_add $HOME/bin/bash-programs-by-ian/utils
154 # note, if I use a machine I don't want files readable by all users, set
155 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
166 if [[ $- == *i* ]]; then
171 # remove any default aliases for these
172 alias ls > /dev/null 2>&1 && unalias ls
173 alias ll > /dev/null 2>&1 && unalias ll
174 alias grep > /dev/null 2>&1 && unalias grep
178 command mkdir -p "$@"
183 complete -A stopped -P '"%' -S '"' d
188 # note: gksudo is recommended for X apps because it does not set the
189 # home directory to the same.
191 if [[ $- == *i* ]]; then
192 # extra space at the end allows aliases to work
193 alias s='SUDOD="$PWD" sudo -i '
196 if [[ $EUID != 0 || $1 == -* ]]; then
207 if [[ $OS == Windows_NT ]]; then
208 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
210 alias j='command cygpath'
211 alias t='command cygstart'
212 alias cygstart='echo be quick, use the alias "t" instead :\)'
213 alias cygpath='echo be quick, use the alias "j" instead :\)'
218 #####################
220 #####################
222 # netselect-apt finds a fast mirror.
223 # but we need to replace the mirrors ourselves,
224 # because it doesn't do that. best it can do is
225 # output a basic sources file
226 # here we get the server it found, get the main server we use
227 # then substitute all instances of one for the other in the sources file
228 # and backup original to /etc/apt/sources.list-original.
230 debian_pick_mirror () {
231 local x=$(mktemp -d)/f # safe way to get file name without creating one
232 sudo netselect-apt -o $x || return 1
233 x=$(_debian_pick_mirror_grep stable $x)
234 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
235 sudo sed -i "s/$(_debian_pick_mirror_grep wheezy)/$x/" /etc/apt/sources.list
238 _debian_pick_mirror_grep () {
239 local x="$(grep -oP "^deb [^ ]+ $1 " ${2-/etc/apt/sources.list})"
242 # replace / with \/ so we can use it with sed
256 if type ack-grep >/dev/null 2>&1; then
262 grep -i --binary-files=without-match --color=auto "$@"
266 grep -ri --binary-files=without-match --color=auto "$@"
272 calc() { echo "scale=3; $*" | bc -l; }
275 # makes it so chown -R symlink affects the symlink and its target.
277 if [[ $1 == -R ]]; then
279 command chown -h "$@"
281 command chown -RH "$@"
291 if [[ $# == 0 ]]; then
292 cp /a/bin/data/COPYING .
294 cp /a/bin/data/COPYING "$@"
300 diff --strip-trailing-cr -w "$@" # diff content
305 if [[ -f /etc/fedora-release ]]; then
308 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
314 date "+%A, %B %d, %r" "$@"
321 envload() { # load environment from a previous: export > file
322 local file=${1:-$HOME/.${USER}_env}
323 eval "$(export | sed 's/^declare -x/export -n/')"
324 while IFS= read -r line; do
325 # declare -x makes variables local to a function
326 eval ${line/#declare -x/export}
332 # havn't tested these:
333 #file cut copy and paste, like the text buffers :)
334 _fbufferinit() { # internal use by
335 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
336 rm -rf "$my_f_tempdir"/*
340 cp "$@" "$my_f_tempdir"/
344 mv "$@" "$my_f_tempdir"/
346 fpst() { # file paste
347 [[ $2 ]] && { echo too many arguments; return 1; }
349 cp "$my_f_tempdir"/* "$target"
353 # find array. make an array of file names found by find into $x
354 # argument: find arguments
355 # return: find results in an array $x
357 while read -rd ''; do
359 done < <(find "$@" -print0);
363 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
364 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
366 gitroot || return 1 # function to set gitroot
368 git symbolic-ref HEAD refs/heads/$1
374 firefox -P default "$@" >/dev/null 2>&1
378 firefox -P alt "$@" >/dev/null 2>&1
385 # horizontal row. used to break up output
386 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
392 # modified from ~/local/bin/git-completion.bash
393 # other completion commands are mostly taken from bash_completion package
394 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
395 || complete -o default -o nospace -F _git i
404 find . -iname '*'"$*"'*'
411 if [[ $PWD == /[iap] ]]; then
412 command ls -A --color=auto -I lost+found "$@"
414 command ls -A --color=auto "$@"
419 lld() { ll -d "$@"; }
422 low() { # make filenames all lowercase
425 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
426 [[ $y != $x ]] && mv "$x" "$y"
431 lower() { # make first letter of filenames lowercase.
434 if [[ ${x::1} == [A-Z] ]]; then
435 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
436 safe_rename "$x" "$y"
442 if [[ $# != 2 ]]; then
443 echo safe_rename error: $# args, need 2 >2
445 elif [[ $1 != $2 ]]; then
447 echo Cannot rename "$1" to "$2" as it already exists.
458 safe_rename "$x" "$y"
464 # aliases would be much more compact, but they can't be used as ssh commands
465 # also, to be used in a script, you need -i which prints annoying
466 # warnings. instead, use -l in a script to source this file
467 if type -p yum > /dev/null; then
469 if [[ $EUID == 0 ]]; then
476 if [[ $EUID == 0 ]]; then
479 sudo yum -y install "$@"
483 if [[ $EUID == 0 ]]; then
491 if [[ $EUID == 0 ]]; then
498 if [[ $EUID == 0 ]]; then
499 aptitude -y install "$@"
501 sudo aptitude -y install "$@"
505 # scratch a very annoying itch.
506 # package description width as wide as the screen, and package name field small
507 # aptitude manual can't figure out how wide emacs terminal is,
508 # of course it doesn't consult the $COLUMNS variable...
509 # and in a normal terminal, it makes the package name field ridiculously big
510 # also, remove that useless dash before the description
511 if [[ $EUID == 0 ]]; then
512 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
514 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
520 # test existence / exists
524 [[ -e "$x" || -L "$x" ]] || ret=1
530 # fix root file ownership for FILE argument.
531 # check if parent or grandparent is not root and if the dir of FILE is also
532 # owned by that user, and change ownership to that user
535 if [[ $EUID == 0 ]]; then
537 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
538 argdir=$(getdir "$1")
539 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
540 if ! chown "--reference=$argdir" "$1"; then
541 echo failed to fix bad ownership file permissons
549 pfind() { #find *$1* in $PATH
550 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
552 IFS=: pathArray=($PATH); unset IFS
553 find "${pathArray[@]}" -iname "*$1*"
557 pwd() { # do pwd + some other info.
558 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
562 pwgen() { # generate a random password, with digits & punctuation and without
564 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
566 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
570 q() { # start / launch a program in the backround and redir output to null
577 exit "$@" 2>/dev/null
580 # trash-restore lists everything that has been trashed at or below CWD
581 # This picks out files just in CWD, not subdirectories,
582 # which also match grep $1, usually use $1 for a time string
583 # which you get from running restore-trash once first
587 # last condition is to not ask again for ones we skipped
588 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
589 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
590 name="$(echo "$name" | head -n $nth | tail -n 1 )"
591 read -p "$name [Y/n] " ask
592 if [[ ! $ask || $ask == [Yy] ]]; then
593 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
594 echo $x | restore-trash > /dev/null
595 elif [[ $ask == [Nn] ]]; then
603 # rsync, root is required to keep permissions right.
604 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
605 # --no-times --delete
606 # basically, make an exact copy, use checksums instead of file times to be more accurate
607 rl() { rsync -ahvic --delete "$@"; }
608 # don't delete files on the target end which do not exist on the original end:
609 rld() { rsync -ahvic "$@"; }
610 complete -F _rsync -o nospace rld rlt fl
611 # rl without preserving modification time. for some reason I had this as default before.
612 # perhaps that reason will come up again and I will document it.
613 rlt() { rsync -ahvic --delete --no-t "$@"; }
617 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
622 complete -F _root_command s sb
624 # use -ll, less secure but faster.
629 # sudo redo. be aware, this command may not work right on strange distros or earlier software
631 if [[ $# == 0 ]]; then
632 sudo -E bash -c -l "$(history -p '!!')"
634 echo this command redos last history item. no argument is accepted
640 # log with script. timing is $1.t and script is $1.s
641 # -l to save to ~/typescripts/
642 # -t to add a timestamp to the filenames
644 local logdir do_stamp arg_base
645 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
648 while getopts "lt" option
651 l ) arg_base=$logdir ;;
655 shift $(($OPTIND - 1))
657 [[ -e $logdir ]] || mkdir -p $logdir
658 $do_stamp && arg_base+=$(date +%F.%T%z)
659 script -t $arg_base.s 2> $arg_base.t
661 splay() { # script replay
662 #logRoot="$HOME/typescripts/"
663 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
664 scriptreplay "$1.t" "$1.s"
671 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
675 ts() { # start editing a new file
676 [[ $# != 1 ]] && echo "I need a filename." && return 1
678 if [[ $- != *i* ]]; then
681 if [[ $1 == *.c ]]; then
682 e '#include <stdio.h>' >"$1"
683 e '#include <stdlib.h>' >>"$1"
684 e 'int main(int argc, char * argv[]) {' >>"$1"
685 e ' printf( "hello world\n");' >>"$1"
686 e ' return 0;' >>"$1"
688 e "${1%.c}: $1" > Makefile
689 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
690 e "#!/bin/bash" >run.sh
691 e "./${1%.c}" >>run.sh
693 elif [[ $1 == *.java ]]; then
694 e "public class ${1%.*} {" >"$1"
695 e ' public static void main(String[] args) {' >>"$1"
696 e ' System.out.println("Hello, world!");' >>"$1"
701 echo "#!/bin/bash" > "$1"
704 [[ $quiet ]] || g "$1"
708 tx() { # toggle set -x, and the prompt so it doesn't spam
709 if [[ $- == *x* ]]; then
711 PROMPT_COMMAND=prompt_command
722 if [[ $OS == Windows_NT ]]; then
733 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
738 if type gvfs-open &> /dev/null ; then
743 # another alternative is run-mailcap
749 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
753 hl() { # history limit. Write extra history to archive file.
754 local max_lines linecount tempfile prune_lines
755 local harchive="${HISTFILE}_archive"
756 for x in "$HISTFILE" "$harchive"; do
757 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
758 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
759 echo "error in hl: history file \$x:$x no good"
763 history -a # save history
764 max_lines=$HISTFILELINES
765 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
766 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
767 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
768 if (($linecount > $max_lines)); then
769 prune_lines=$(($linecount - $max_lines))
770 head -n $prune_lines "$HISTFILE" >> "$harchive" \
771 && sed -ie "1,${prune_lines}d" $HISTFILE
775 if [[ $- == *i* ]]; then
776 # commands to run when bash exits normally
781 # temporary variables to test colorization
782 # some copied from gentoo /etc/bash/bashrc,
784 # dircolors --print-database uses its own built-in database
785 # instead of using /etc/DIR_COLORS. Try to use the external file
786 # first to take advantage of user additions.
787 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
789 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
790 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
791 [[ -z ${match_lhs} ]] \
792 && type -P dircolors >/dev/null \
793 && match_lhs=$(dircolors --print-database)
794 # test if our $TERM is in the TERM values in dircolor
795 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
798 if ${use_color} && [[ $- == *i* ]]; then
800 if [[ $XTERM_VERSION == Cygwin* ]]; then
804 underl) echo -n $'\E[4m' ;;
805 bold) echo -n $'\E[1m' ;;
806 red) echo -n $'\E[31m' ;;
807 green) echo -n $'\E[32m' ;;
808 blue) echo -n $'\E[34m' ;;
809 cyan) echo -n $'\E[36m' ;;
810 yellow) echo -n $'\E[33m' ;;
811 purple) echo -n $'\E[35m' ;;
812 nocolor) echo -n $'\E(B\E[m' ;;
821 underl) echo -n $(tput smul) ;;
822 bold) echo -n $(tput bold) ;;
823 red) echo -n $(tput setaf 1) ;;
824 green) echo -n $(tput setaf 2) ;;
825 blue) echo -n $(tput setaf 4) ;;
826 cyan) echo -n $(tput setaf 6) ;;
827 yellow) echo -n $(tput setaf 3) ;;
828 purple) echo -n $(tput setaf 5) ;;
829 nocolor) echo -n $(tput sgr0) ;; # no font attributes
839 # Try to keep environment pollution down, EPA loves us.
840 unset safe_term match_lhs use_color
852 if [[ $- == *i* ]]; then
853 # git branch/status prompt function
854 if [[ $OS != Windows_NT ]]; then
855 GIT_PS1_SHOWDIRTYSTATE=true
857 # arch source location
858 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
859 # fedora/debian source
860 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
862 # in case we didn't source git-prompt.sh
863 if ! declare -f __git_ps1 > /dev/null; then
869 # this needs to come before next ps1 stuff
870 # this stuff needs bash 4, feb 2009,
871 # old enough to no longer condition on $BASH_VERSION anymore
875 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
877 bind -m vi-command B:shell-backward-word
878 bind -m vi-command W:shell-forward-word
881 if [[ $SSH_CLIENT ]]; then
886 local return=$? # this MUST COME FIRST
888 local ps_char ps_color
890 history -a # save history
891 history -n # read any new history
892 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
893 # from the screen man page
894 if [[ $TERM == screen* ]]; then
895 local title_escape="\033]..2;"
897 local title_escape="\033]0;"
899 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
903 0) ps_color="$(get_term_color blue)"
906 1) ps_color="$(get_term_color green)"
907 ps_char="$return \\$"
909 *) ps_color="$(get_term_color yellow)"
910 ps_char="$return \\$"
913 if [[ ! -O . ]]; then # not owner
914 if [[ -w . ]]; then # writable
915 ps_color="$(get_term_color bold red)"
917 ps_color="$(get_term_color bold green)"
920 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
922 PROMPT_COMMAND=prompt_command
926 ###########################################
927 # stuff that makes sense to be at the end #
928 ###########################################
929 if [[ "$SUDOD" ]]; then
931 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
940 # if someone exported $SOE, catch errors