.bashrc's

Show me your underwear /s

I've been working on adapting mine from a few different distros, mostly Manjaro, because they include a lot of useful tools.

# .bashrc
# random helpful startup stuff from Manjaro.

if [[ $- != *i* ]] ; then
	# Shell is non-interactive.  Be done now!
	return
fi

xhost +local:root > /dev/null 2>&1
complete -cf sudo

# Bash won't get SIGWINCH if another process is in the foreground.
# Enable checkwinsize so that bash will check the terminal size when
# it regains control.  #65623
# http://cnswww.cns.cwru.edu/~chet/bash/FAQ (E11)
shopt -s checkwinsize
shopt -s expand_aliases
shopt -s histappend

case ${TERM} in
	xterm*|rxvt*|Eterm*|aterm|kterm|gnome*|interix|konsole*)
		PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\007"'
		;;
	screen*)
		PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\033\\"'
		;;
esac

# Set colorful PS1 only on colorful terminals.
# dircolors --print-database uses its own built-in database
# instead of using /etc/DIR_COLORS.  Try to use the external file
# first to take advantage of user additions.  Use internal bash
# globbing instead of external grep binary.
use_color=false
safe_term=${TERM//[^[:alnum:]]/?}   # sanitize TERM
match_lhs=""
[[ -f ~/.dir_colors   ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
[[ -z ${match_lhs}    ]] \
	&& type -P dircolors >/dev/null \
	&& match_lhs=$(dircolors --print-database)
[[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true

# from Ubuntu

# don't put duplicate lines or lines starting with space in the history.
HISTCONTROL=ignoreboth
export GCC_COLORS='error01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# custom user functions

style () {
        style=0
        case $1 in
                bold)  style=1 ;;
                uline) style=4 ;;
                *)     style=0 ;;
        esac
        printf "\e[$(echo $style)m"
}

color () {
        case $1 in
                black)  printf "\033[30m" ;;
                red)    printf "\033[31m" ;;
                green)  printf "\033[32m" ;;
                yellow) printf "\033[33m" ;;
                blue)   printf "\033[34m" ;;
                purple) printf "\033[35m" ;;
                cyan)   printf "\033[36m" ;;
                white)  printf "\033[37m" ;;
                *)      printf "\e[m"     ;;
        esac
}

# color script is Manjaro, the rest is my own

if $use_color ; then
        if type -P dircolors >/dev/null ; then
                if [[ -f ~/.dir_colors ]] ; then
                        eval $(dircolors -b ~/.dir_colors)
                elif [[ -f /etc/DIR_COLORS ]] ; then
                        eval $(dircolors -b /etc/DIR_COLORS)
                fi
        fi

        # custom PS1's

        if [ "$EUID" == "0" ] ; then
            PS1='$(power=$? ; if [[ $power == 0 ]]; then echo "$(color yellow)[$(color;style bold)\h$(style):$(style bold;color blue)\w$(style;color yellow)]$(color)"; else echo "$(color red)[$(color)$power $(style bold)\h$(color;style):$(style bold;color blue)\w$(style;color red)]$(color)"; fi)# ' # root PS1
        else
            PS1='$(power=$? ; if [[ $power == 0 ]]; then echo "$(color green)[\u$(color)@$(style bold)\h$(style):$(style bold;color blue)\w$(style;color green)]$(color)"; else echo "$(color red)[$(color)$power $(color green)\u$(color)@$(style bold)\h$(style):$(style bold;color blue)\w$(style;color red)]$(color)"; fi)$ ' # user PS1
        fi

        # color-dependent aliases
        alias    ls='ls --color=always'
        alias    ll='ls -A --color=always'
        alias    la='ls -lAF --color=always'
	alias  grep='grep --color=always'
	alias fgrep='fgrep --color=always'
	alias egrep='egrep --color=always'

else
        # custom PS1's
        if [ "$EUID" == "0" ] ; then
                PS1='$(power=$? ; if [[ $power == 0 ]]; then echo "[\h:\w]"; else echo "[$power \h:\w]"; fi)# ' # root PS1
        else
                PS1='$(power=$? ; if [[ $power == 0 ]]; then echo "[\u@\h:\w]"; else echo "[$power \u@\h:\w]"; fi)$ ' # user PS1
        fi

        # aliases
        alias ll='ls -A'
        alias la='ls -lAF'
fi

unset use_color safe_term match_lhs

# useful functions from distro's

ex () { # attr: Manjaro
        if [ -f $1 ] ; then
                case $1 in
                        *.tar.bz2)   tar xjf $1   ;;
                        *.tar.gz)    tar xzf $1   ;;
                        *.bz2)       bunzip2 $1   ;;
                        *.rar)       unrar x $1   ;;
                        *.gz)        gunzip $1    ;;
                        *.tar)       tar xf $1    ;;
                        *.tbz2)      tar xjf $1   ;;
                        *.tgz)       tar xzf $1   ;;
                        *.zip)       unzip $1     ;;
                        *.Z)         uncompress $1;;
                        *.7z)        7z x $1      ;;
                        *)           echo "'$1' cannot be extracted via ex()" ;;
                esac
        else
                echo "'$1' is not a valid file"
        fi
}

# color-independent aliases
alias    cp="cp -i"
alias    df="df -h"
alias  free="free -m"
alias  pang="ping -c 5 8.8.8.8"
alias rfind="2>/dev/null find / -name"

# intro output
echo "$(style bold)$(uname -n)$(style): $(uname -o)" ; uname -r ; bash --version | grep --color=never -oE "^(.*release)" ; date +"%b %d, %Y %T" ; echo

Here's what it looks like when I open a terminal, use root, with errors and such:

What sort of modifications have made to your .bashrc? Use any cool PS1's?

2 Likes

Awesome sauce. Clearly a very involved rc, mad props.

This sounds super lame but the only changes I make to my bashrc is adding powerline. Mainly out of laziness.... runs away and hides

Haha, that's fine, probably better, because I spend a little too much time thinking about how I could be doing my everyday scripting more efficiently. I'm crazy enough to make an alias for ping -c 5 8.8.8.8 just so I don't have to type it out every time.

1 Like

most of mine is pretty basic, the manual bits are

export EDITOR=vim
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'
alias l='ls -CFV'
alias rmov='rsync --remove-source-files'
#alias wake='sudo etherwake -b <mac-address of my other computers> -i wlan0'

# alert: send notifications from bash scripts
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# duh: sort files and folders after size
duh () 
{ 
    [ $# -eq 0 ] && du -sh * | sort -h;
    [ $# -gt 0 ] && du -sh "$@" | sort -h
}
# duha: same as duh, but for hidden files
alias duha='du -sh .[!.]*|sort -h'


# spawn: Launch application quietly (ie. don't mess up my terminal with debug output)
# usage: spawn evince book.pdf
#        spawn eog image.jpg
function spawn() {
    (exec 0</dev/null 1>/dev/null 2>/dev/null "$@")&
}
function _spawn() {
    local cur prev
    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}
    if [ $(type -t _command)z = "function"z ]; then
        _command # requires bash-completion
    else
# If bash-completion is not installed:
        case "$prev" in
            spawn) COMPREPLY=($(compgen -c -- $cur)) ;;
                *) COMPREPLY=($(compgen -f -- $cur)) ;;
        esac
    fi
}
complete -F _spawn spawn

# open: open file in default application
# usage: open book.pdf
#        open image.png
#        open document.odt
open () 
{ 
    for i in "$@";
    do
        ( spawn xdg-open "$i" );
    done
}

# lsflash: Lists active flash videos
# usage: mpv $(lsflash)
#        cp $(lsflash) save_dir/
function lsflash() {
    sudo lsof -X -c dwb -c opera -c plugin-c -c chromium -c chrome 2>/dev/null| grep Flash |grep -v '.so'|awk '{print "/proc/"$2"/fd/"int($4)}'
}

# patrol: Run command when file changes
function patrol() {
    file=$1; shift
    echo patrolling $file...
    type $1 &> /dev/null || $1 || return $?
    while true; do
        if [ -e $file ]; then
             $@; inotifywait -e modify $file
         else
            sleep 1
        fi
    done
}

# Man page colours:
export LESS_TERMCAP_mb=$'\E[01;31m'       # begin blinking
export LESS_TERMCAP_md=$'\E[01;38;5;74m'  # begin bold
export LESS_TERMCAP_me=$'\E[0m'           # end mode
export LESS_TERMCAP_se=$'\E[0m'           # end standout-mode
export LESS_TERMCAP_so=$'\E[38;5;246m'    # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\E[0m'           # end underline
export LESS_TERMCAP_us=$'\E[04;38;5;146m' # begin underline
export LESS=cR

# awesome dir jumper
# z.sh
. ~/bin/z
alias z='_z 2>&1'

# Organize my movies (uses filebot)
# usage: fixtv My_tvSeries/
#        fixtv My_AmbiguousSeries/ -non-strict
fixtv ()
{
    filebot -r --format "$PWD/{n}/Season {s}/{sxe}.{t.space(\".\")}" --db TheTVDB -rename "$@"
    for i in "$@"
    do
        if [ ! -e "$i" ]
        then
            continue
        fi
        ls -R "$i"
        echo -n "Do you wish to delete $i [y/N] "
        read reply
        if [ "z$reply" = "zy" ]
        then
            echo removing $i...
            rm -r -- "$i"
        fi 
    done
}
2 Likes

Cool! I think I've seen that spawn function before - normally I just disable all output and make it a daemon. There's still a little output from the daemon, but I can still kill it if I want.

There's a lot of interesting sort functions there, too. Nice!

Here's my .bashrc, nothing too fancy:

alias ls='ls --color=auto'
#archbey -c white
#~/scripts/test.sh
#~/scripts/blocks.sh

export EDITOR="vim"

color-blocks () {   
    echo
    local width=$(( ($COLUMNS / 16) -1 ))
    local chars
    local pre=$(( ( $COLUMNS - ($width+1)*16)/2 ))
    for ((i=0; i<$width; i++)); do chars+="โ–‘" ; done
    for ((i=0; i<$pre; i++)); do echo -n " " ; done
    for ((i=0; i<=7; i++)); do echo -en "\e[3${i}m${chars} \e[1;3${i}m${chars}\e[m "; done; echo; echo
    unset i
}

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
bakgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset


if [ "$DISPLAY" != "" ]; then
    if ( pidof urxvt > /dev/null ); then
        PS1="\[$bldylw\]\u\[$txtrst\] | \[$txtgrn\]\t \[$txtrst\]| \[$bldpur\]\w \n\[$txtrst\] >> "
    elif ( pidof lxterminal > /dev/null ); then
        PS1="\[$txtcyn\]โ”Œโ”€ \[$bldylw\]\u\[$txtgrn\] - \[$bldred\]\t\[$txtgrn\] - \[$bldpur\]\w\[$txtcyn\] 
\[$txtcyn\]โ””โ”€\[$txtrst\]$\[$txtcyn\]โ”€ยป\[$txtrst\] "
    elif ( pidof lxterminal > /dev/null ) && ( pidof xterm > /dev/null ); then
        echo "Sia xterm che lxterminal sono in esecuzione"
        PS1="\[$bldylw\]\u\[$txtrst\] | \[$txtgrn\]\t \[$txtrst\]| \[$bldpur\]\w \n\[$txtrst\] >> "
    else
        PS1="\[$txtcyn\]โ”Œโ”€ \[$bldylw\]\u\[$txtgrn\] - \[$bldred\]\t\[$txtgrn\] - \[$bldpur\]\w\[$txtcyn\] 
\[$txtcyn\]โ””โ”€\[$txtrst\]$\[$txtcyn\]โ”€ยป\[$txtrst\] "
    fi
fi

2 Likes

Damn thats sexy 9/11.

Updated for the month of november, gone are my days of power line(yay).

# /etc/skel/.bashrc
#
# This file is sourced by all *interactive* bash shells on startup,
# including some apparently interactive shells such as scp and rcp
# that can't tolerate any output.  So make sure this doesn't display
# anything or bad things will happen !


# Test for an interactive shell.  There is no need to set anything
# past this point for scp and rcp, and it's important to refrain from
# outputting anything in those cases.
if [[ $- != *i* ]] ; then
    # Shell is non-interactive.  Be done now!
    return
fi


# Put your fun stuff here.
# don't put duplicate lines or lines starting with space in the history.
HISTCONTROL=ignoreboth

# Add to history instead of overriding it
shopt -s histappend

# History lenght
HISTSIZE=1000
HISTFILESIZE=2000

# Window size sanity check
shopt -s checkwinsize

# User/root variables definition
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# Colored XTERM promp
case "$TERM" in
    xterm-color) color_prompt=yes;;
esac

# Colored prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    color_prompt=yes
    else
    color_prompt=
    fi
fi

# Prompt
if [ -n "$SSH_CONNECTION" ]; then
export PS1="\[$(tput setaf 1)\]โ”Œโ”€โ•ผ \[$(tput setaf 7)\][\w]\n\[$(tput setaf 1)\]\$(if [[ \$? == 0 ]]; then echo \"\[$(tput setaf 1)\]โ””โ”€โ”€โ”€โ”€โ•ผ \[$(tput setaf 7)\][ssh]\"; else echo \"\[$(tput setaf 1)\]โ””โ•ผ \[$(tput setaf 7)\][ssh]\"; fi) \[$(tput setaf 7)\]"
else
export PS1="\[$(tput setaf 1)\]โ”Œโ”€โ•ผ \[$(tput setaf 7)\][\w]\n\[$(tput setaf 1)\]\$(if [[ \$? == 0 ]]; then echo \"\[$(tput setaf 1)\]โ””โ”€โ”€โ”€โ”€โ•ผ\"; else echo \"\[$(tput setaf 1)\]โ””โ•ผ\"; fi) \[$(tput setaf 7)\]"
fi

trap 'echo -ne "\e[0m"' DEBUG

# I this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# Color support
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
fi

# Alias definitions.
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# Auto-completion 
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

# Advanced directory creation
function mkcd {
  if [ ! -n "$1" ]; then
    echo "Entrez un nom pour ce dossier"
  elif [ -d $1 ]; then
    echo "\`$1' existe dรฉjร "
  else
    mkdir $1 && cd $1
  fi
}

# Go back with ..
b() {
    str=""
    count=0
    while [ "$count" -lt "$1" ];
    do
        str=$str"../"
        let count=count+1
    done
    cd $str
}

# Color man pages
man() {
    env \
        LESS_TERMCAP_mb=$(printf "\e[1;31m") \
        LESS_TERMCAP_md=$(printf "\e[1;31m") \
        LESS_TERMCAP_me=$(printf "\e[0m") \
        LESS_TERMCAP_se=$(printf "\e[0m") \
        LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
        LESS_TERMCAP_ue=$(printf "\e[0m") \
        LESS_TERMCAP_us=$(printf "\e[1;32m") \
            man "$@"
}

# Auto cd
shopt -s autocd

# ls after a cd
function cd()
{
 builtin cd "$*" && ls
}

extract () {
    if [ -f $1 ] ; then
      case $1 in
        *.tar.bz2)   tar xjf $1     ;;
        *.tar.gz)    tar xzf $1     ;;
        *.bz2)       bunzip2 $1     ;;
        *.rar)       unrar e $1     ;;
        *.gz)        gunzip $1      ;;
        *.tar)       tar xf $1      ;;
        *.tbz2)      tar xjf $1     ;;
        *.tgz)       tar xzf $1     ;;
        *.zip)       unzip $1       ;;
        *.Z)         uncompress $1  ;;
        *.7z)        7z x $1        ;;
        *)     echo "'$1' cannot be extracted via extract()" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}`

Update to mine, I added a couple of functions to manage daemons.

dae () {
	chmod +x $1 # just in case it's not already executable (careful)
	daeout=$2
	if [ -z $daeout ] ; then daeout=/dev/null ; fi
 	setsid $1 >$daeout 2>&1 < /dev/null &
}

kill_dae () {
	daeproc=$(ps -fade | grep $1 | grep -v grep | awk '{print $2}')
	if [ "$(ps --no-headers s $daeproc | wc -l)" == 1 ] ; then
		kill $daeproc
		echo "agent $daeproc out of service."
	else
		echo "bad process name - try being more or less specific"
	fi
}

I'm also working on something that saves specific files to a server and I can call sync to get up to date for my different computers. I haven't gotten it working yet, though.

Haha, I remember when I first started using Linux I was so confused why it didn't say anything when I changed directories. Now I guess I'm so used to it I don't even think about that anymore. That's useful, thanks.

1 Like

Everyone had that moment when they started lol

I never did and still dont really muck around much with my bashrc's (i'm lazy and shit at scripting). but i did start on this to make dealing with different files through the terminal a bit more fluid.

# Fuck my life
open () {
    if [ -f $1 ] ; then
      case $1 in
         *.txt)       leafpad $1    ;;
         *.mp3)     mocp $1         ;;
         *.png)     ristretto $1    ;;
          esac
      fi
}

P.S i'm the biggest scripting noob. so if you have any hints or tips(you are the CS major here) it would be gratefully accepted .

Doesn't Linux typically have a xdg-open command you could use? I mean, not to distract you from scripting, but...

Sure, I'll look closer, try to nitpick.

you could just use a for loop instead.

for count in $(seq 1 $1); do str=$str"../"; done

1 Like

I just enjoy mucking around with bash scripts and i thought it would be something i could do to try some new idea's.
i have never read any guides on learning about bash scripting so i usually just sit down with a beer and make this shit up as i go along. entertainment at its best eh?

Oh and cheers for the nit picking :)

1 Like

Don't worry about it. You're not alone!

I literally use 'g' and 'gi' as aliases for 'grep' and 'grep -i' haha

I was procrastinating on my paper, so I wrote a base conversion function. Surprisingly fun!

# convert value $1 from base $2 to base $3 (default 10)
convertbase () {
	# Who needs two assoc arrays when you can be clever? Also, makes it easier to add more
	terminlist=(0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O)
	# warning: if expanding with lowercase letters, you should change the third line below
	#   to deprecate dynamic case binding: "${1^^}" to "$1"
	termoutlist () {
		for each in ${!terminlist[@]} ; do
			if [[ "${terminlist[$each]}" == "${1^^}" ]] ; then
				echo $each
				return
			fi
		done
	}

	# only convert from base10 if user says it is not in base10
	val=0
	if [[ $2 != 10 ]] ; then
                # basically, uh, sum all (column * (base)^(nth from right starting at 0))
		# ex: 1101 (in base 2) = 1*2^3 + 1*2^2 + 0+2^1 + 1*2^0 = 8 + 4 + 0 + 1 = 13
	        for i in $(seq 0 $((${#1}-1))) ; do
			let val+=$(($(termoutlist ${1:i:1})*$(($2**$((${#1}-$(($i+1))))))))
		done
	else
		val=$1
	fi

	# private recursive function to convert val to base$2
	#   (seems like the easiest way to do it)
	tobase () {
		if [[ $1 -lt $2 ]] ; then
			echo ${terminlist[$1]}
		else
			echo "$(tobase $((${1}/${2})) $2)${terminlist[$((${1}%${2}))]}"
		fi
	}

	if [[ $# -ge 3 && $3 != 10 ]] ; then
		echo $(tobase $val $3)
	else
		echo $val
	fi
}

A very basic and easy addon to my bashrc I realy like:

alias cexit='cat /dev/null > ~/.bash_history && history -c && exit'

Makes a clean exit of the shell. The nulling of .bash_history is needad as history -c wont do the trick alone on ubuntu.

This will clear out your history, right? So, for example, the next time you entered the shell the up arrow wouldn't do anything?

1 Like

Yep.

I've got some really basic additions.

alias gp=git pull
gc() {
  git clone [email protected]:companyname/$*
}
clean() {
  git clean --force -d
  git reset --hard origin/master
}

There's also a couple of aliases for cloning a few commonly-used Git repos using Momdan and 2-3 commands to SSH into servers.