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.
94 if [[ $INSIDE_EMACS ]]; then
98 # for readline-complete.el
103 if [[ $- == *i* ]]; then
104 # for readline-complete.el
105 if [[ $INSIDE_EMACS ]]; then
106 bind 'set horizontal-scroll-mode on'
107 bind 'set print-completions-horizontally on'
109 # arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
110 if [[ $TERM == "xterm" ]]; then
111 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
112 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
114 bind '"\eOc": shell-forward-word'
115 bind '"\eOd": shell-backward-word'
117 # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
118 # gnome-terminal, overridden by bash, or disabled by the system
119 stty werase undef lnext undef stop undef start undef
126 # history number. History expansion is good.
128 # history file size limit, set to unlimited.
129 # this needs to be different from the default because
130 # default HISTFILESIZE is 500 and could clobber our history
132 # max commands 1 session can append/read from history
134 # my own history size limit based on lines
135 HISTFILELINES=1000000
137 # the time format display when doing the history command
138 # also, setting this makes the history file record time
139 # of each command as seconds from the epoch
140 HISTTIMEFORMAT="%I:%M %p %m/%d "
141 # consecutive duplicate lines don't go in history
142 HISTCONTROL=ignoredups
143 # just defensively unsetting this
144 # this var can replace HISTCONTROL to do more flexible things like
145 # not saving single char history items or specific names
148 export BC_LINE_LENGTH=0
150 path_add --ifexists /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
151 path_add $HOME/bin/bash-programs-by-ian/utils
152 # note, if I use a machine I don't want files readable by all users, set
153 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
164 if [[ $- == *i* ]]; then
169 # remove any default aliases for these
170 alias ls > /dev/null 2>&1 && unalias ls
171 alias ll > /dev/null 2>&1 && unalias ll
172 alias grep > /dev/null 2>&1 && unalias grep
176 command mkdir -p "$@"
181 complete -A stopped -P '"%' -S '"' d
186 # note: gksudo is recommended for X apps because it does not set the
187 # home directory to the same.
189 if [[ $- == *i* ]]; then
190 # extra space at the end allows aliases to work
191 alias s='SUDOD="$PWD" sudo -i '
194 if [[ $EUID != 0 || $1 == -* ]]; then
205 if [[ $OS == Windows_NT ]]; then
206 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
208 alias j='command cygpath'
209 alias t='command cygstart'
210 alias cygstart='echo be quick, use the alias "t" instead :\)'
211 alias cygpath='echo be quick, use the alias "j" instead :\)'
216 #####################
218 #####################
232 if type ack-grep >/dev/null 2>&1; then
238 grep -i --binary-files=without-match --color=auto "$@"
242 grep -ri --binary-files=without-match --color=auto "$@"
248 calc() { echo "scale=3; $*" | bc -l; }
251 # makes it so chown -R symlink affects the symlink and its target.
253 if [[ $1 == -R ]]; then
255 command chown -h "$@"
257 command chown -RH "$@"
267 if [[ $# == 0 ]]; then
268 cp /a/bin/data/COPYING .
270 cp /a/bin/data/COPYING "$@"
276 diff --strip-trailing-cr -w "$@" # diff content
281 if [[ -f /etc/fedora-release ]]; then
284 grep "^ID=.*" /etc/os-release | sed 's/^ID=//'
290 date "+%A, %B %d, %r" "$@"
297 envload() { # load environment from a previous: export > file
298 local file=${1:-$HOME/.${USER}_env}
299 eval "$(export | sed 's/^declare -x/export -n/')"
300 while IFS= read -r line; do
301 # declare -x makes variables local to a function
302 eval ${line/#declare -x/export}
308 # havn't tested these:
309 #file cut copy and paste, like the text buffers :)
310 _fbufferinit() { # internal use by
311 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
312 rm -rf "$my_f_tempdir"/*
316 cp "$@" "$my_f_tempdir"/
320 mv "$@" "$my_f_tempdir"/
322 fpst() { # file paste
323 [[ $2 ]] && { echo too many arguments; return 1; }
325 cp "$my_f_tempdir"/* "$target"
329 # find array. make an array of file names found by find into $x
330 # argument: find arguments
331 # return: find results in an array $x
333 while read -rd ''; do
335 done < <(find "$@" -print0);
339 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
340 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
342 gitroot || return 1 # function to set gitroot
344 git symbolic-ref HEAD refs/heads/$1
350 firefox -P default "$@" >/dev/null 2>&1
354 firefox -P alt "$@" >/dev/null 2>&1
361 # horizontal row. used to break up output
362 hr() { printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq $COLUMNS); }
368 # modified from ~/local/bin/git-completion.bash
369 # other completion commands are mostly taken from bash_completion package
370 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
371 || complete -o default -o nospace -F _git i
380 find . -iname '*'"$*"'*'
387 if [[ $PWD == /[iap] ]]; then
388 command ls -A --color=auto -I lost+found "$@"
390 command ls -A --color=auto "$@"
395 lld() { ll -d "$@"; }
398 low() { # make filenames all lowercase
401 y=$(tr "[A-Z]" "[a-z]" <<<"$x")
402 [[ $y != $x ]] && mv "$x" "$y"
407 lower() { # make first letter of filenames lowercase.
410 if [[ ${x::1} == [A-Z] ]]; then
411 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
412 safe_rename "$x" "$y"
418 if [[ $# != 2 ]]; then
419 echo safe_rename error: $# args, need 2 >2
421 elif [[ $1 != $2 ]]; then
423 echo Cannot rename "$1" to "$2" as it already exists.
434 safe_rename "$x" "$y"
438 # force symbolic link creation.
439 # trash-put any existing files where links would be created.
440 # mkdir -p the directory containing the link(s) if needed.
441 # then do ln -s -- "$@"
443 if [[ $# -gt 2 && ! -d ${!#} ]]; then
446 if [[ $# -gt 1 && -d ${!#} ]]; then
449 for x in "${@:1:$(($#-1))}"; do # all but last arg
450 # remove any trailing slashes
452 # remove any leading directory components
454 te "$x" && trash-put "$x"
457 elif [[ $# -eq 2 ]]; then
460 elif [[ ! -d $(getdir "$2") ]]; then
461 mkdir -p $(getdir "$2")
464 te "${1##*/}" && rm "${1##*/}"
472 # aliases would be much more compact, but they can't be used as ssh commands
473 # also, to be used in a script, you need -i which prints annoying
474 # warnings. instead, use -l in a script to source this file
475 if type -p yum > /dev/null; then
477 if [[ $EUID == 0 ]]; then
484 if [[ $EUID == 0 ]]; then
487 sudo yum -y install "$@"
491 if [[ $EUID == 0 ]]; then
499 if [[ $EUID == 0 ]]; then
506 if [[ $EUID == 0 ]]; then
507 aptitude -y install "$@"
509 sudo aptitude -y install "$@"
513 # scratch a very annoying itch.
514 # package description width as wide as the screen, and package name field small
515 # aptitude manual can't figure out how wide emacs terminal is,
516 # of course it doesn't consult the $COLUMNS variable...
517 # and in a normal terminal, it makes the package name field ridiculously big
518 # also, remove that useless dash before the description
519 if [[ $EUID == 0 ]]; then
520 aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
522 sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
528 # test existence / exists
532 [[ -e "$x" || -L "$x" ]] || ret=1
538 # fix root file ownership for FILE argument.
539 # check if parent or grandparent is not root and if the dir of FILE is also
540 # owned by that user, and change ownership to that user
543 if [[ $EUID == 0 ]]; then
545 if [[ $(stat -c "%u" "$1") == 0 ]] ; then
546 argdir=$(getdir "$1")
547 if [[ $(stat -c "%u" "$argdir") != 0 ]] ; then
548 if ! chown "--reference=$argdir" "$1"; then
549 echo failed to fix bad ownership file permissons
557 pfind() { #find *$1* in $PATH
558 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
560 IFS=: pathArray=($PATH); unset IFS
561 find "${pathArray[@]}" -iname "*$1*"
565 pwd() { # do pwd + some other info.
566 echo "$(ll -d "$PWD") $USER@$HOSTNAME $(date +%r)"
570 pwgen() { # generate a random password, with digits & punctuation and without
572 head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c "$arg"
574 head -c 200 /dev/urandom | tr -cd '[:alnum:]' | head -c "$arg"
578 q() { # start / launch a program in the backround and redir output to null
585 exit "$@" 2>/dev/null
588 # trash-restore lists everything that has been trashed at or below CWD
589 # This picks out files just in CWD, not subdirectories,
590 # which also match grep $1, usually use $1 for a time string
591 # which you get from running restore-trash once first
595 # last condition is to not ask again for ones we skipped
596 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
597 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
598 name="$(echo "$name" | head -n $nth | tail -n 1 )"
599 read -p "$name [Y/n] " ask
600 if [[ ! $ask || $ask == [Yy] ]]; then
601 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
602 echo $x | restore-trash > /dev/null
603 elif [[ $ask == [Nn] ]]; then
611 # rsync, root is required to keep permissions right.
612 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
613 # --no-times --delete
614 # basically, make an exact copy, use checksums instead of file times to be more accurate
615 rl() { rsync -ahvic --delete "$@"; }
616 # don't delete files on the target end which do not exist on the original end:
617 rld() { rsync -ahvic "$@"; }
618 complete -F _rsync -o nospace rld rlt fl
619 # rl without preserving modification time. for some reason I had this as default before.
620 # perhaps that reason will come up again and I will document it.
621 rlt() { rsync -ahvic --delete --no-t "$@"; }
625 # use sb instead of s is for sudo redirections, eg. sb 'echo "ok fine" > /etc/file'
630 complete -F _root_command s sb
632 # use -ll, less secure but faster.
637 # sudo redo. be aware, this command may not work right on strange distros or earlier software
639 if [[ $# == 0 ]]; then
640 sudo -E bash -c -l "$(history -p '!!')"
642 echo this command redos last history item. no argument is accepted
648 # log with script. timing is $1.t and script is $1.s
649 # -l to save to ~/typescripts/
650 # -t to add a timestamp to the filenames
652 local logdir do_stamp arg_base
653 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
656 while getopts "lt" option
659 l ) arg_base=$logdir ;;
663 shift $(($OPTIND - 1))
665 [[ -e $logdir ]] || mkdir -p $logdir
666 $do_stamp && arg_base+=$(date +%F.%T%z)
667 script -t $arg_base.s 2> $arg_base.t
669 splay() { # script replay
670 #logRoot="$HOME/typescripts/"
671 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
672 scriptreplay "$1.t" "$1.s"
679 (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
683 ts() { # start editing a new file
684 [[ $# != 1 ]] && echo "I need a filename." && return 1
686 if [[ $- != *i* ]]; then
689 if [[ $1 == *.c ]]; then
690 e '#include <stdio.h>' >"$1"
691 e '#include <stdlib.h>' >>"$1"
692 e 'int main(int argc, char * argv[]) {' >>"$1"
693 e ' printf( "hello world\n");' >>"$1"
694 e ' return 0;' >>"$1"
696 e "${1%.c}: $1" > Makefile
697 e " g++ -ggdb -std=gnu99 -o ${1%.c} $<" >> Makefile
698 e "#!/bin/bash" >run.sh
699 e "./${1%.c}" >>run.sh
701 elif [[ $1 == *.java ]]; then
702 e "public class ${1%.*} {" >"$1"
703 e ' public static void main(String[] args) {' >>"$1"
704 e ' System.out.println("Hello, world!");' >>"$1"
709 echo "#!/bin/bash" > "$1"
712 [[ $quiet ]] || g "$1"
716 tx() { # toggle set -x, and the prompt so it doesn't spam
717 if [[ $- == *x* ]]; then
719 PROMPT_COMMAND=prompt_command
730 if [[ $OS == Windows_NT ]]; then
741 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
746 if type gvfs-open &> /dev/null ; then
751 # another alternative is run-mailcap
757 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
761 hl() { # history limit. Write extra history to archive file.
762 local max_lines linecount tempfile prune_lines
763 local harchive="${HISTFILE}_archive"
764 for x in "$HISTFILE" "$harchive"; do
765 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
766 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
767 echo "error in hl: history file \$x:$x no good"
771 history -a # save history
772 max_lines=$HISTFILELINES
773 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
774 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
775 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
776 if (($linecount > $max_lines)); then
777 prune_lines=$(($linecount - $max_lines))
778 head -n $prune_lines "$HISTFILE" >> "$harchive" \
779 && sed -ie "1,${prune_lines}d" $HISTFILE
783 # commands to run when bash exits normally
787 # temporary variables to test colorization
788 # some copied from gentoo /etc/bash/bashrc,
790 # dircolors --print-database uses its own built-in database
791 # instead of using /etc/DIR_COLORS. Try to use the external file
792 # first to take advantage of user additions.
793 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
795 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
796 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
797 [[ -z ${match_lhs} ]] \
798 && type -P dircolors >/dev/null \
799 && match_lhs=$(dircolors --print-database)
800 # test if our $TERM is in the TERM values in dircolor
801 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
804 if ${use_color} && [[ $- == *i* ]]; then
806 if [[ $XTERM_VERSION == Cygwin* ]]; then
810 underl) echo -n $'\E[4m' ;;
811 bold) echo -n $'\E[1m' ;;
812 red) echo -n $'\E[31m' ;;
813 green) echo -n $'\E[32m' ;;
814 blue) echo -n $'\E[34m' ;;
815 cyan) echo -n $'\E[36m' ;;
816 yellow) echo -n $'\E[33m' ;;
817 purple) echo -n $'\E[35m' ;;
818 nocolor) echo -n $'\E(B\E[m' ;;
827 underl) echo -n $(tput smul) ;;
828 bold) echo -n $(tput bold) ;;
829 red) echo -n $(tput setaf 1) ;;
830 green) echo -n $(tput setaf 2) ;;
831 blue) echo -n $(tput setaf 4) ;;
832 cyan) echo -n $(tput setaf 6) ;;
833 yellow) echo -n $(tput setaf 3) ;;
834 purple) echo -n $(tput setaf 5) ;;
835 nocolor) echo -n $(tput sgr0) ;; # no font attributes
845 # Try to keep environment pollution down, EPA loves us.
846 unset safe_term match_lhs use_color
858 if [[ $- == *i* ]]; then
859 # git branch/status prompt function
860 if [[ $OS != Windows_NT ]]; then
861 GIT_PS1_SHOWDIRTYSTATE=true
863 # arch source location
864 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
865 # fedora/debian source
866 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
868 # in case we didn't source git-prompt.sh
869 if ! declare -f __git_ps1 > /dev/null; then
875 # this needs to come before next ps1 stuff
876 if [[ $BASH_VERSION == [456789]* ]]; then
881 if [[ $- == *i* ]] && [[ ! $INSIDE_EMACS ]]; then
883 bind -m vi-command B:shell-backward-word
884 bind -m vi-command W:shell-forward-word
890 if [[ $SSH_CLIENT ]]; then
895 local return=$? # this MUST COME FIRST
897 local ps_char ps_color
899 history -a # save history
900 history -n # read any new history
901 if [[ ! DESKTOP_SESSION == xmonad && $TERM == *(screen*|xterm*|rxvt*) ]]; then
902 # from the screen man page
903 if [[ $TERM == screen* ]]; then
904 local title_escape="\033]..2;"
906 local title_escape="\033]0;"
908 echo -ne "$title_escape${PWD/#$HOME/~} $USER@$HOSTNAME\007"
912 0) ps_color="$(get_term_color blue)"
915 1) ps_color="$(get_term_color green)"
916 ps_char="$return \\$"
918 *) ps_color="$(get_term_color yellow)"
919 ps_char="$return \\$"
922 if [[ ! -O . ]]; then # not owner
923 if [[ -w . ]]; then # writable
924 ps_color="$(get_term_color bold red)"
926 ps_color="$(get_term_color bold green)"
929 PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
931 PROMPT_COMMAND=prompt_command
935 ###########################################
936 # stuff that makes sense to be at the end #
937 ###########################################
938 if [[ "$SUDOD" ]]; then
940 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
949 # if someone exported $SOE, catch errors