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
101 # todo, remote file completion fails, figure out how to turn it off
105 if [[ $- == *i* ]]; then
106 # for readline-complete.el
107 if [[ $INSIDE_EMACS ]]; then
108 bind 'set horizontal-scroll-mode on'
109 bind 'set print-completions-horizontally on'
110 bind '"\C-i": self-insert'
112 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
113 if [[ $TERM == "xterm" ]]; then
114 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
115 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
117 bind '"\eOc": shell-forward-word'
118 bind '"\eOd": shell-backward-word'
120 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
121 # gnome-terminal, overridden by bash, or disabled by the system
122 stty werase undef lnext undef stop undef start undef
129 # history number. History expansion is good.
131 # history file size limit, set to unlimited.
132 # this needs to be different from the default because
133 # default HISTFILESIZE is 500 and could clobber our history
135 # max commands 1 session can append/read from history
137 # my own history size limit based on lines
138 HISTFILELINES=1000000
140 # the time format display when doing the history command
141 # also, setting this makes the history file record time
142 # of each command as seconds from the epoch
143 HISTTIMEFORMAT="%I:%M %p %m/%d "
144 # consecutive duplicate lines don't go in history
145 HISTCONTROL=ignoredups
146 # works in addition to HISTCONTROL to do more flexible things
147 # it could also do the same things as HISTCONTROL and thus replace it,
151 export BC_LINE_LENGTH=0
153 path_add --ifexists /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
154 path_add $HOME/bin/bash-programs-by-ian/utils
155 # note, if I use a machine I don't want files readable by all users, set
156 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
167 if [[ $- == *i* ]]; then
172 # remove any default aliases for these
173 alias ls > /dev/null 2>&1 && unalias ls
174 alias ll > /dev/null 2>&1 && unalias ll
175 alias grep > /dev/null 2>&1 && unalias grep
179 command mkdir -p "$@"
184 complete -A stopped -P '"%' -S '"' d
189 # note: gksudo is recommended for X apps because it does not set the
190 # home directory to the same.
192 if [[ $- == *i* ]]; then
193 # extra space at the end allows aliases to work
194 alias s='SUDOD="$PWD" sudo -i '
197 if [[ $EUID != 0 || $1 == -* ]]; then
208 if [[ $OS == Windows_NT ]]; then
209 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
211 alias j='command cygpath'
212 alias t='command cygstart'
213 alias cygstart='echo be quick, use the alias "t" instead :\)'
214 alias cygpath='echo be quick, use the alias "j" instead :\)'
219 #####################
221 #####################
223 # netselect-apt finds a fast mirror.
224 # but we need to replace the mirrors ourselves,
225 # because it doesn't do that. best it can do is
226 # output a basic sources file
227 # here we get the server it found, get the main server we use
228 # then substitute all instances of one for the other in the sources file
229 # and backup original to /etc/apt/sources.list-original.
231 debian_pick_mirror () {
232 local x=$(mktemp -d)/f # safe way to get file name without creating one
233 sudo netselect-apt -o "$x" || return 1
234 x=$(_debian_pick_mirror_grep stable "$x")
235 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
236 sudo sed -i "s/$(_debian_pick_mirror_grep wheezy)/$x/" /etc/apt/sources.list
240 _debian_pick_mirror_grep () {
241 local x="$(grep -oP "^deb [^ ]+ $1 " ${2-/etc/apt/sources.list})"
244 # replace / with \/ so we can use it with sed
258 if type ack-grep >/dev/null 2>&1; then
264 grep -i --binary-files=without-match --color=auto "$@"
268 grep -ri --binary-files=without-match --color=auto "$@"
272 local startdir="$PWD"
276 tar cz bin/bash-programs-by-ian bin/semi-private .profile | ssh $x tar xz
279 cp ~/path_add-function ~/.bashrc ~/.bash_profile ~/.profile ~/.bashrc_profile .
281 tar cz path_add-function .bashrc | ssh $x tar xz
287 k() { grep -P "$@" ${HISTFILE:-~/.bash_history} | tail -n 40; }
289 calc() { echo "scale=3; $*" | bc -l; }
292 # makes it so chown -R symlink affects the symlink and its target.
294 if [[ $1 == -R ]]; then
296 command chown -h "$@"
298 command chown -RH "$@"
308 if [[ $# == 0 ]]; then
309 cp /a/bin/data/COPYING .
311 cp /a/bin/data/COPYING "$@"
317 diff --strip-trailing-cr -w "$@" # diff content
322 if [[ -f /etc/fedora-release ]]; then
325 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
331 date "+%A, %B %d, %r" "$@"
338 envload() { # load environment from a previous: export > file
339 local file=${1:-$HOME/.${USER}_env}
340 eval "$(export | sed 's/^declare -x/export -n/')"
341 while IFS= read -r line; do
342 # declare -x makes variables local to a function
343 eval ${line/#declare -x/export}
349 # havn't tested these:
350 #file cut copy and paste, like the text buffers :)
351 _fbufferinit() { # internal use by
352 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
353 rm -rf "$my_f_tempdir"/*
357 cp "$@" "$my_f_tempdir"/
361 mv "$@" "$my_f_tempdir"/
363 fpst() { # file paste
364 [[ $2 ]] && { echo too many arguments; return 1; }
366 cp "$my_f_tempdir"/* "$target"
370 # find array. make an array of file names found by find into $x
371 # argument: find arguments
372 # return: find results in an array $x
374 while read -rd ''; do
376 done < <(find "$@" -print0);
380 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
381 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
383 gitroot || return 1 # function to set gitroot
384 builtin cd "$gitroot"
385 git symbolic-ref HEAD refs/heads/$1
391 firefox -P default "$@" >/dev/null 2>&1
395 firefox -P alt "$@" >/dev/null 2>&1
402 # horizontal row. used to break up output
403 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
409 # modified from ~/local/bin/git-completion.bash
410 # other completion commands are mostly taken from bash_completion package
411 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
412 || complete -o default -o nospace -F _git i
421 find . -iname '*'"$*"'*'
428 if [[ $PWD == /[iap] ]]; then
429 command ls -A --color=auto -I lost+found "$@"
431 command ls -A --color=auto "$@"
436 lld() { ll -d "$@"; }
439 low() { # make filenames all lowercase
442 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
443 [[ $y != $x ]] && mv "$x" "$y"
448 lower() { # make first letter of filenames lowercase.
451 if [[ ${x::1} == [A-Z] ]]; then
452 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
453 safe_rename "$x" "$y"
459 if [[ $# != 2 ]]; then
460 echo safe_rename error: $# args, need 2 >2
462 elif [[ $1 != $2 ]]; then
464 echo Cannot rename "$1" to "$2" as it already exists.
475 safe_rename "$x" "$y"
481 # aliases would be much more compact, but they can't be used as ssh commands
482 # also, to be used in a script, you need -i which prints annoying
483 # warnings. instead, use -l in a script to source this file
484 if type -p yum > /dev/null; then
486 if [[ $EUID == 0 ]]; then
493 if [[ $EUID == 0 ]]; then
496 sudo yum -y install "$@"
500 if [[ $EUID == 0 ]]; then
508 if [[ $EUID == 0 ]]; then
515 if [[ $EUID == 0 ]]; then
516 aptitude -y install "$@"
518 sudo aptitude -y install "$@"
522 # scratch a very annoying itch.
523 # package description width as wide as the screen, and package name field small
524 # aptitude manual can't figure out how wide emacs terminal is,
525 # of course it doesn't consult the $COLUMNS variable...
526 # and in a normal terminal, it makes the package name field ridiculously big
527 # also, remove that useless dash before the description
528 if [[ $EUID == 0 ]]; then
529 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
531 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
537 # test existence / exists
541 [[ -e "$x" || -L "$x" ]] || ret=1
547 # fix root file ownership for FILE argument.
548 # check if parent or grandparent is not root and if the dir of FILE is also
549 # owned by that user, and change ownership to that user
552 if [[ $EUID == 0 ]]; then
553 te "$1" || touch "$1"
554 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
555 argdir=$(getdir "$1")
556 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
557 if ! chown "--reference=$argdir" "$1"; then
558 echo failed to fix bad ownership file permissons
566 pfind() { #find *$1* in $PATH
567 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
569 IFS=: pathArray=($PATH); unset IFS
570 find "${pathArray[@]}" -iname "*$1*"
574 pwd() { # do pwd + some other info.
575 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
579 pwgen() { # generate a random password, with digits & punctuation and without
581 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
583 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
587 q() { # start / launch a program in the backround and redir output to null
594 exit "$@" 2>/dev/null
597 # trash-restore lists everything that has been trashed at or below CWD
598 # This picks out files just in CWD, not subdirectories,
599 # which also match grep $1, usually use $1 for a time string
600 # which you get from running restore-trash once first
604 # last condition is to not ask again for ones we skipped
605 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
606 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
607 name="$(echo "$name" | head -n $nth | tail -n 1 )"
608 read -p "$name [Y/n] " ask
609 if [[ ! $ask || $ask == [Yy] ]]; then
610 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
611 echo $x | restore-trash > /dev/null
612 elif [[ $ask == [Nn] ]]; then
620 # rsync, root is required to keep permissions right.
621 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
622 # --no-times --delete
623 # basically, make an exact copy, use checksums instead of file times to be more accurate
624 rl() { rsync -ahvic --delete "$@"; }
625 # don't delete files on the target end which do not exist on the original end:
626 rld() { rsync -ahvic "$@"; }
627 complete -F _rsync -o nospace rld rlt fl
628 # rl without preserving modification time. for some reason I had this as default before.
629 # perhaps that reason will come up again and I will document it.
630 rlt() { rsync -ahvic --delete --no-t "$@"; }
634 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
639 complete -F _root_command s sb
641 # use -ll, less secure but faster.
646 # sudo redo. be aware, this command may not work right on strange distros or earlier software
648 if [[ $# == 0 ]]; then
649 sudo -E bash -c -l "$(history -p '!!')"
651 echo this command redos last history item. no argument is accepted
657 # log with script. timing is $1.t and script is $1.s
658 # -l to save to ~/typescripts/
659 # -t to add a timestamp to the filenames
661 local logdir do_stamp arg_base
662 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
665 while getopts "lt" option
668 l ) arg_base=$logdir ;;
672 shift $(($OPTIND - 1))
674 [[ -e $logdir ]] || mkdir -p $logdir
675 $do_stamp && arg_base+=$(date +%F.%T%z)
676 script -t $arg_base.s 2> $arg_base.t
678 splay() { # script replay
679 #logRoot="$HOME/typescripts/"
680 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
681 scriptreplay "$1.t" "$1.s"
688 (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
692 ts() { # start editing a new file
693 [[ $# != 1 ]] && echo "I need a filename." && return 1
695 if [[ $- != *i* ]]; then
698 if [[ $1 == *.c ]]; then
699 e '#include <stdio.h>' >"$1"
700 e '#include <stdlib.h>' >>"$1"
701 e 'int main(int argc, char * argv[]) {' >>"$1"
702 e ' printf( "hello world\n");' >>"$1"
703 e ' return 0;' >>"$1"
705 e "${1%.c}: $1" > Makefile
706 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
707 e "#!/bin/bash" >run.sh
708 e "./${1%.c}" >>run.sh
710 elif [[ $1 == *.java ]]; then
711 e "public class ${1%.*} {" >"$1"
712 e ' public static void main(String[] args) {' >>"$1"
713 e ' System.out.println("Hello, world!");' >>"$1"
718 echo "#!/bin/bash" > "$1"
721 [[ $quiet ]] || g "$1"
725 tx() { # toggle set -x, and the prompt so it doesn't spam
726 if [[ $- == *x* ]]; then
728 PROMPT_COMMAND=prompt_command
739 if [[ $OS == Windows_NT ]]; then
750 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
755 if type gvfs-open &> /dev/null ; then
760 # another alternative is run-mailcap
766 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
770 hl() { # history limit. Write extra history to archive file.
771 local max_lines linecount tempfile prune_lines
772 local harchive="${HISTFILE}_archive"
773 for x in "$HISTFILE" "$harchive"; do
774 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
775 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
776 echo "error in hl: history file \$x:$x no good"
780 history -a # save history
781 max_lines=$HISTFILELINES
782 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
783 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
784 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
785 if (($linecount > $max_lines)); then
786 prune_lines=$(($linecount - $max_lines))
787 head -n $prune_lines "$HISTFILE" >> "$harchive" \
788 && sed -ie "1,${prune_lines}d" $HISTFILE
792 if [[ $- == *i* ]]; then
793 # commands to run when bash exits normally
798 # temporary variables to test colorization
799 # some copied from gentoo /etc/bash/bashrc,
801 # dircolors --print-database uses its own built-in database
802 # instead of using /etc/DIR_COLORS. Try to use the external file
803 # first to take advantage of user additions.
804 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
806 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
807 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
808 [[ -z ${match_lhs} ]] \
809 && type -P dircolors >/dev/null \
810 && match_lhs=$(dircolors --print-database)
811 # test if our $TERM is in the TERM values in dircolor
812 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
815 if ${use_color} && [[ $- == *i* ]]; then
817 if [[ $XTERM_VERSION == Cygwin* ]]; then
821 underl) echo -n $'\E[4m' ;;
822 bold) echo -n $'\E[1m' ;;
823 red) echo -n $'\E[31m' ;;
824 green) echo -n $'\E[32m' ;;
825 blue) echo -n $'\E[34m' ;;
826 cyan) echo -n $'\E[36m' ;;
827 yellow) echo -n $'\E[33m' ;;
828 purple) echo -n $'\E[35m' ;;
829 nocolor) echo -n $'\E(B\E[m' ;;
838 underl) echo -n $(tput smul) ;;
839 bold) echo -n $(tput bold) ;;
840 red) echo -n $(tput setaf 1) ;;
841 green) echo -n $(tput setaf 2) ;;
842 blue) echo -n $(tput setaf 4) ;;
843 cyan) echo -n $(tput setaf 6) ;;
844 yellow) echo -n $(tput setaf 3) ;;
845 purple) echo -n $(tput setaf 5) ;;
846 nocolor) echo -n $(tput sgr0) ;; # no font attributes
856 # Try to keep environment pollution down, EPA loves us.
857 unset safe_term match_lhs use_color
869 if [[ $- == *i* ]]; then
870 # git branch/status prompt function
871 if [[ $OS != Windows_NT ]]; then
872 GIT_PS1_SHOWDIRTYSTATE=true
874 # arch source location
875 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
876 # fedora/debian source
877 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
879 # in case we didn't source git-prompt.sh
880 if ! declare -f __git_ps1 > /dev/null; then
886 # this needs to come before next ps1 stuff
887 # this stuff needs bash 4, feb 2009,
888 # old enough to no longer condition on $BASH_VERSION anymore
892 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
894 bind -m vi-command B:shell-backward-word
895 bind -m vi-command W:shell-forward-word
898 if [[ $SSH_CLIENT ]]; then
903 local return=$? # this MUST COME FIRST
905 local ps_char ps_color
907 history -a # save history
908 history -n # read any new history
909 if [[ ! $DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
910 # from the screen man page
911 if [[ $TERM == screen* ]]; then
912 local title_escape="\033]..2;"
914 local title_escape="\033]0;"
916 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
920 0) ps_color="$(get_term_color blue)"
923 1) ps_color="$(get_term_color green)"
924 ps_char="$return \\$"
926 *) ps_color="$(get_term_color yellow)"
927 ps_char="$return \\$"
930 if [[ ! -O . ]]; then # not owner
931 if [[ -w . ]]; then # writable
932 ps_color="$(get_term_color bold red)"
934 ps_color="$(get_term_color bold green)"
937 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
939 PROMPT_COMMAND=prompt_command
943 ###########################################
944 # stuff that makes sense to be at the end #
945 ###########################################
946 if [[ "$SUDOD" ]]; then
948 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
957 # if someone exported $SOE, catch errors