Skip to content

Instantly share code, notes, and snippets.

@scriptum
Created September 22, 2015 09:41
Show Gist options
  • Select an option

  • Save scriptum/5f4162f1bf683e5a4d64 to your computer and use it in GitHub Desktop.

Select an option

Save scriptum/5f4162f1bf683e5a4d64 to your computer and use it in GitHub Desktop.
#!/bin/sh
# source global definitions
[[ -f /etc/bashrc ]] && . /etc/bashrc
# toggle keyboard layout with caps lock
setxkbmap -option grp:caps_toggle
# enable core dumps
# ulimit -S -c unlimited
# disable core dumps
ulimit -S -c 0
# something that shouldn't be public
[[ -f $HOME/.bashrc_private ]] && . $HOME/.bashrc_private
# ignore case in glob
# shopt -s nocaseglob
function __prompt_command_generator() {
PS1=""
PS1+='$(__LAST_EXIT="$?";' # This needs to be first
local TXTRED='\[\e[0;31m\]' # red
local TXTGRN='\[\e[0;32m\]' # green
local TXTYLW='\[\e[0;33m\]' # yellow
local TXTBLU='\[\e[0;34m\]' # blue
local TXTPUR='\[\e[0;35m\]' # purple
local TXTCYN='\[\e[0;36m\]' # cyan
local TXTWHT='\[\e[0;37m\]' # white
local BLDRED='\[\e[1;31m\]' # red - Bold
local BLDGRN='\[\e[1;32m\]' # green
local BLDYLW='\[\e[1;33m\]' # yellow
local BLDBLU='\[\e[1;34m\]' # blue
local BLDPUR='\[\e[1;35m\]' # purple
local BLDCYN='\[\e[1;36m\]' # cyan
local BLDWHT='\[\e[1;37m\]' # white
local TXTRST='\[\e[0m\]' # Text reset
#mark root as red
PS1+='[[ $UID -eq 0 ]] && echo -n "'$TXTRED'" || echo -n "'$TXTCYN'";'
PS1+='echo -n "\u'$TXTRST'";'
#hide host name if we are on a local machine
if [[ -n "$SSH_CLIENT" || -n "$SSH_TTY" ]]; then
PS1+='echo -n "@'$TXTYLW'\h'$TXTRST'";'
fi
#append current path
PS1+='echo -n " '$BLDBLU'\W";'
#append git branch
if type -p git>/dev/null; then
PS1+='__GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2> /dev/null);'
PS1+='[[ -n "$__GIT_BRANCH" ]] && echo -n "'$TXTBLU'(${__GIT_BRANCH})";'
PS1+='unset __GIT_BRANCH;'
fi
#show exit code
PS1+='[[ $__LAST_EXIT -eq 0 ]] && echo -n "'$BLDGRN'" || echo -n "'$BLDRED'";';
PS1+='unset __LAST_EXIT)'
PS1+="\\\$ $TXTRST"
}
# we do not need use this in non-interactive terminals e.g. scp
if [[ $- == *i* ]]; then
# unset if defined system-wide
unset PROMPT_COMMAND
__prompt_command_generator
fi
unset __prompt_command_generator
# add /usr/local/lib because some distro doesn not do that
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
# $HOME/.bin - for my binaries
# $HOME/.nimble/bin - trick for nim support
# /usr/lib64/icecc/bin - intel compiler
export PATH=/opt/intel/bin:/usr/lib64/icecc/bin:$HOME/.bin:$HOME/.nimble/bin:$PATH
# increase history
export HISTSIZE=100000
export HISTFILESIZE=10000000
# skip duplicates in history e.g. thousands of ls
export HISTCONTROL=erasedups
# grep over history
alias hs='history | grep --color=auto -i'
# works bad
# export HISTIGNORE="?:??:git push -f:top:git status:git pull:cd -:cd ..:exit:pwd:clear:mount:umount:[ \t]*"
# favorite editor
_MY_EDITOR=geany
# make make parallel - number of processors * 2
alias make="make -j$(($(nproc)*2))"
# alias e="file-roller --extract-here"
type -p colordif > /dev/null && alias diff='colordiff'
if type -p git > /dev/null; then # git
# git aliases incluging mistypes
alias ga='git add'
alias gb='git branch -a'
alias gca='git commit --amend'
alias gc='git commit -m'
alias gco='git checkout'
alias gd='git diff --color'
alias gdt='git difftool -y'
alias gl='git log --oneline --color'
alias gpf='git push -f'
alias gp='git pull; git push'
alias gr='git remote -v'
alias пз='git pull; git push'
alias gs='git status'
alias пы='git status'
if ! type -p __git_complete > /dev/null; then
__git_complete(){
complete -o default -o nospace -F $2 $1
}
fi
__git_complete ga _git_add
__git_complete gb _git_branch
__git_complete gca _git_commit
__git_complete gc _git_commit
__git_complete gco _git_checkout
__git_complete gd _git_diff
__git_complete gpf _git_push
__git_complete gp _git_push
__git_complete gr _git_remote
__git_complete gs _git_status
# rebase whole git to change author
git-author() {
git filter-branch -f --commit-filter 'case $GIT_COMMITTER_NAME in $_MY_NAME_PATTERN) GIT_COMMITTER_NAME=$_MY_NAME GIT_COMMITTER_EMAIL=$_MY_MAIL GIT_AUTHOR_NAME=$_MY_NAME GIT_AUTHOR_EMAIL=$_MY_MAIL git commit-tree "$@";; *) git commit-tree "$@";; esac'
}
# search unmerged branches
git-unmerged() {
git branch -r --no-merged | grep -v HEAD | xargs -L1 git --no-pager log --pretty=tformat:'%Cgreen%d%Creset - %h by %an (%Cblue%ar%Creset)' -1
}
# open git project in github
gh() {
o "$(git remote -v | grep origin | awk 'NR==1{print $2}' | sed -r 's|git@(.*):|https://\1/|')" >& /dev/null
}
fi # end of git
# traditional output style for profiler
type -p gprof > /dev/null && alias gprof='gprof -T'
alias xtar='tar -xvf'
alias service='sudo service'
if type -p nim nimble > /dev/null; then # nim
alias nbi='nimble install'
alias nbs='nimble search'
alias nimr='nim c --gc:boehm -d:release'
alias nimc='nim c --gc:boehm'
fi # end of nim
alias g=$_MY_EDITOR
alias ll='ls -laFvh --color=auto'
alias pstree='pstree -apl'
alias pgrep='pgrep -l'
alias grep='grep --color=auto -i'
# alias cppcheck="$HOME/git/cppcheck/cppcheck -q -j4 --max-configs=1 --template=gcc"
# alias check-gtk="$HOME/git/cppcheck/cppcheck -q -j4 --max-configs=1 --template=gcc --library=gtk --append=$HOME/git/cppcheck-libs/gtk.h"
# alias mycheck="$HOME/git/cppcheck/cppcheck -q -j16 --max-configs=1 --template=gcc --std=posix"
alias mycheck_full="$HOME/git/cppcheck/cppcheck -q -j16 --enable=performance,portability,information,warning --max-configs=1 --inconclusive --template=gcc --library=gtk --std=posix"
# alias cppcheck="$HOME/git/cppcheck/cppcheck -q -j16 --enable=performance,portability,information,warning,style --max-configs=1 --inconclusive --template=gcc --library=gtk --std=posix"
alias mycheck_everything="$HOME/git/cppcheck/cppcheck -q -j16 --enable=performance,portability,information,warning --max-configs=1 --inconclusive --template=gcc --std=posix"
alias cppcheck="$HOME/git/cppcheck/cppcheck -q -j16 --enable=performance,portability,information,warning --max-configs=1 --inconclusive --template=gcc --std=posix --library=gtk"
#alias geany="LC_LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 geany"
if type -p rpm > /dev/null; then # rpm
_distro=$(echo $(lsb_release -d 2> /dev/null | awk -F: '{print $2}'))
if [[ $_distro == Mageia* ]]; then
# pseudo-yum
alias yi='sudo urpmi --auto'
alias ys='urpmq -y'
alias ye='sudo urpme'
else
#yum aliases
_yum_aliased()
{
let COMP_CWORD+=1
}
alias yca='sudo yum clean all'
alias ye='sudo yum remove'
alias yi='sudo yum install -y'
alias yp='yum provides'
alias yr='sudo yum reinstall -y'
alias ys='yum search'
alias yu='sudo yum update -y'
fi
alias rpmlast='rpm -qa --qf "%{N}\n" --last'
alias ql='rpm -ql'
alias qa='rpm -qa'
alias qag='rpmqa | grep --color=auto -i'
# rpm package by file name
qf() {
if [[ -f $1 ]]; then
rpm -qf "$1"
else
rpm -qf "$(type -p "$1")"
fi
}
# fast package list
rpmqa() {
cat <<EOF | python
import bsddb
F="/var/lib/rpm/Name"
try:
it = bsddb.btopen(F, 'r')
except:
it = bsddb.hashopen(F, 'r')
for k in it:
if k.startswith('$1'): print k
EOF
}
alias i='rpm -qi'
alias qi='rpm -qi'
alias rpmtop='rpm -qa --qf "%-15{SIZE}%{NVRA}\n" | sort -nr | head'
if [[ -f /var/lib/rpm/Name ]]; then
# fast version of rpm -qa for autocompletion
_rpm_installed_packages() {
local cur prev words cword split
_init_completion -s || return
COMPREPLY=( $( compgen -W "$(rpmqa)" -- "$cur" ) )
}
fi
complete -F _rpm_installed_packages ql i qi ye yu
fi #end of rpm
# aliases for cd including some common mistypes
alias cd..='cd ..'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'
alias dc='cd'
alias св='cd'
type -p xdg-open > /dev/null && alias o='xdg-open'
type -p exo-open > /dev/null && alias o='exo-open'
# reload bashrc
alias .b='. ~/.bashrc'
# edit bashrc
alias rced="$_MY_EDITOR ~/.bashrc"
alias bc='bc -l'
# do not show russian man pages?
# alias man="LANG=C LC_ALL=C man"
dush() {
case $# in
0) du -sh ./* | sort -h;;
1) du -sh "$1"/* | sort -h;;
*) du -sh "$@" | sort -h;;
esac
}
if type -p scanimage scantailor-cli > /dev/null; then # scanimage
# scanner! you need to install scantailor-cli
alias scan-single="scanimage --mode Gray --resolution 300 > out.pnm && mogrify -unsharp 0x4+5 out.pnm && scantailor-cli --content-detection=cautious out.pnm . && convert -density 300 -compress Fax out.tif out.pdf && rm out.tif out.pnm"
alias scan-adf="rm -f out-*.pnm; scanimage --mode Gray --resolution 300 --source ADF --batch=out-%04d.pnm; mogrify -unsharp 0x4+5 out-*.pnm && scantailor-cli --content-detection=cautious out-*.pnm . && convert -density 300 -compress Fax out-*.tif out.pdf && rm out-*.tif"
alias scan-duplex="rm -f out-*.pnm; scanimage --mode Gray --resolution 300 --source Duplex --batch=out-%04d.pnm; mogrify -unsharp 0x4+5 out-*.pnm && scantailor-cli --content-detection=cautious out-*.pnm . && convert -density 300 -compress Fax out-*.tif out.pdf && rm out-*.tif"
fi #end of scanimage
# search anything in c/c++ source
src() {
grep -iInRs \
'--include=*.'{[ch]{,pp,xx,++},h[hp],c[cp],tcc,[CH],CPP,i,ii} \
"$@" . 2> /dev/null
}
# search anything in python source
srp() {
grep -iInRs '--include=*.py' "$@" . 2> /dev/null
}
# search anything
sr() {
local inc
# e.g. sr *.m4 SOME_MACRO
while [[ $1 == \** ]]; do
inc="$inc --include=$1"
shift
done
grep -iInRs --exclude-dir=.git --exclude-dir=.svn $inc "$@" . 2> /dev/null
}
# retrieve nth field from file
fld() {
awk '{print $'$1'}'
}
# find files/dirs by name
f() {
find -type f -iname "*$@*" 2> /dev/null
}
ff() {
find -type f -iname "$@*" 2> /dev/null
}
fe() {
find -type f -iname "*$@" 2> /dev/null
}
fd() {
find -type d -iname "*$@*" 2> /dev/null
}
# get frequency of nth field in file, e.g.:
# - most frequent letter: fold -w1 /etc/passwd | freq
# - cut -d: -f7 /etc/passwd | freq
# - groups in /dev: ls -l /dev | freq 4
freq() {
local n=0
[[ $# -ge 1 ]] && n="$1"
# use awk - it allows to get fields
awk '{d[$'$n']++}END{for(k in d){printf "%10d %s\n", d[k], k}}' | sort -n
}
if [[ -x /usr/bin/gs ]]; then
# just pdf optimizer
pdf-optimize()
{
for f in "$@"
do
TMP=$(mktemp)
SIZE_OLD=$(wc -c < "$f")
echo "Optimizing '$f' of size $SIZE_OLD"
/usr/bin/gs \
-sDEVICE=pdfwrite \
-dCompatibilityLevel=1.4 \
-dPDFSETTINGS=/ebook \
-dDetectDuplicateImages=true \
-dNOPAUSE \
-dBATCH \
-dQUIET \
-sOutputFile="$TMP" \
"$f"
SIZE_NEW=$(wc -c < "$TMP")
if [ $(echo "$SIZE_NEW > $SIZE_OLD" | bc) = "1" ]
then
echo "New size ($SIZE_NEW) is bigger, skipping"
/bin/rm "$TMP"
else
echo "New size: $SIZE_NEW"
mv "$f" "$f".bak
mv "$TMP" "$f"
fi
done
}
fi # end of gs
# for time - it shows seconds, not minutes:seconds
export TIMEFORMAT=$'\nreal\t%3R\nuser\t%3U\nsys\t%3S'
# protection from accidentally mistyped rm. Use rrm for "old" rm
[[ $(type -p rm) == "" ]] && unalias rm 2>/dev/null
__RMTHREAD=""
rm()
{
local threshold=10
if [[ $1 == "-fr" || $1 == "-rf" || $# -gt $threshold ]]; then
local sec=10
{(
echo "Через $sec сек. будут удалены файлы:"
echo "$@"
sleep $sec
/bin/rm "$@"
)& disown;} 2>/dev/null
__RMTHREAD=$!
echo "Наберите $(tput bold)mr$(tput sgr0) для отмены"
else
/bin/rm "$@"
fi
}
mr()
{
kill $__RMTHREAD 2>/dev/null
__RMTHREAD=""
}
rrm()
{
/bin/rm "$@"
}
if type -p ffmpeg > /dev/null; then # ffmpeg
# parallel convert all audio to ogg
# WARNING! May overwrite old files
toogg() {
# find -name '*.mp3' -print0 | xargs -0 -n1 -P$(nproc) \
# sh -c 'echo "$0"; \
# ffmpeg -v quiet -y -i "$0" \
# -acodec libvorbis -ab 112k -vn "${0%mp3}ogg"'
find -type f -print0 | xargs -0 -n8 -P$(nproc) file -F/ | grep -i '/[^/]*audio' | sed 's@/[^/]*$@@' | xargs -d"\n" -n1 -P$(nproc) sh -c 'echo "$0";T=$(mktemp ./XXXX.ogg); ffmpeg -v quiet -y -i "$0" -vn -acodec libvorbis -ab 96k "$T"; mv "$T" "${0%.*}.ogg"'
}
# parallel convert all audio to mp3
# WARNING! May overwrite old files
tomp3() {
find -type f -print0 | xargs -0 -n8 -P$(nproc) file -F/ | grep -i '/[^/]*audio' | sed 's@/[^/]*$@@' | xargs -d"\n" -n1 -P$(nproc) sh -c 'echo "$0";T=$(mktemp ./XXXX.mp3); ffmpeg -v quiet -y -i "$0" -vn -codec libmp3lame -ab 128k "$T"; mv "$T" "${0%.*}.mp3"'
# find -name '*.flac' -print0 | xargs -0 -n1 -P$(nproc) sh -c 'echo "$0"; ffmpeg -v quiet -y -i "$0" -vn -codec libmp3lame -ab 128k "${0%.*}.mp3"'
}
fi # end of ffmpeg
if type -p optipng advdef advpng > /dev/null; then
png-optimize() {
find -name '*.png' -type f -print0 | xargs -0 -P$(nproc) -I{} \
sh -c 'S="{} $(wc -c < "{}") -> "; optipng -quiet -o2 "{}"; advdef -q -z -4 "{}"; advpng -q -z -4 "{}"; echo "$S $(wc -c < "{}")"'
}
png-optimize-extreme() {
find -name '*.png' -type f -print0 | xargs -0 -P$(nproc) -I{} sh -c 'optipng -quiet -o1 "{}"; advpng -q -z -4 -i100 "{}" || advdef -q -z -4 -i100 "{}"; echo "{}"'
}
fi # end of png optimize
if type -p jpegtran > /dev/null; then
jpg-optimize() {
find -name '*.jpg' -type f -print0 | xargs -0 -P$(nproc) -I{} \
sh -c 'OS=$(wc -c < "{}"); T="$(mktemp)"; \
jpegtran -copy none -progressive -optimize "{}" > "$T"; \
if [[ $? -eq 0 ]]; then \
NS=$(wc -c < "$T");\
if [[ $NS -gt $OS ]]; then \
rm "$T"; NS=$OS; \
else \
mv "$T" "{}"; \
fi; \
printf "%-30s %10s -> %-10s\n" "{}" "$OS" "$NS"; \
else rm "$T"; \
fi'
}
fi # end of jpegtran
# http://stackoverflow.com/questions/29954852/bash-completion-honor-repository-specific-git-alias-in-alias-completion
CompletableAlias() {
if (($#<2)); then
return 1
fi
source_c="$1"
target_c="$2"
target_a=( "${@:2}" )
target_s="${target_a[*]}"
alias "${source_c}=${target_s}"
completion_modifier="__${source_c}_completion"
completion_original="$( complete -p "$target_c" 2>/dev/null |
sed 's/.*-F\W\+\(\w\+\).*/\1/'
)"
if [[ -n "$completion_original" ]]; then
read -r -d '' completion_function <<-EOF
function $completion_modifier() {
COMP_LINE="\${COMP_LINE/#${source_c}/${target_s}}"
((COMP_POINT+=${#target_s}-${#source_c}))
((COMP_CWORD+=${#target_a[@]}-1))
COMP_WORDS=( ${target_a[@]} \${COMP_WORDS[@]:1} )
$completion_original
}
EOF
eval "$completion_function"
completion_command="$( complete -p "$target_c" |
sed "s/${completion_original}/${completion_modifier}/;
s/\w\+\$/${source_c}/"
)"
$completion_command
fi
}
# http://unix.stackexchange.com/questions/4219/how-do-i-get-bash-completion-for-command-aliases
function make-completion-wrapper () {
local function_name="$2"
local arg_count=$(($#-3))
local comp_function_name="$1"
shift 2
local function="
function $function_name {
((COMP_CWORD+=$arg_count))
COMP_WORDS=( "$@" \${COMP_WORDS[@]:1} )
"$comp_function_name"
return 0
}"
eval "$function"
echo $function_name
echo "$function"
}
# google search
gg() {
o "https://google.com/search?q=$*" >& /dev/null
}
# increase completions limit
bind 'set completion-query-items 5000' 2> /dev/null
# search in history with arrows
bind '"\e[A": history-search-backward' 2> /dev/null
bind '"\e[B": history-search-forward' 2> /dev/null
# show list automatically, without double tab
bind 'set show-all-if-ambiguous on' 2> /dev/null
# reduce memory usage by GTK apps
export G_SLICE=always-malloc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment