What's in your .bashrc?

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
Jamesc359

What's in your .bashrc?

Post by Jamesc359 »

Because I spend a lot of time at the command line and ssh I've added a few things to my .bashrc file to make life a little easier. Of course I added a few helper scripts too. :-)

I'm curious to hear if anybody has any cool aliases or etc.

.bashrc

Code: Select all

# ALIASES
####################

alias ps='ps auxf'
alias pg='ps aux | grep'

# LIST DIRECTORIES
alias lsd='ls -l | grep --color=never "^d" | awk '\''{
	split($0,a," "); 
	for(i=8; i<=length(a); ++i)
	{
		printf "%s",a[i];
		if(i<length(a)) printf " ";
	}
	printf "\n"
	}'\'' | column'

# LIST ALL DIRECTORIES
alias lsda='ls -lA | grep --color=never "^d" | awk '\''{
	split($0,a," "); 
	for(i=8; i<=length(a); ++i)
	{
		printf "%s",a[i];
		if(i<length(a)) printf " ";
	}
	printf "\n"
	}'\'' | column'

# LIST FILES
alias lsf='ls -l | grep --color=never -v "^d" | awk '\''{
	split($0,a," "); 
	for(i=8; i<=length(a); ++i)
	{
		printf "%s",a[i];
		if(i<length(a)) printf " ";
	}
	printf "\n"
	}'\'' | column'
	
# LIST ALL FILES 
alias lsfa='ls -lA | grep --color=never -v "^d" | awk '\''{
	split($0,a," "); 
	for(i=8; i<=length(a); ++i)
	{
		printf "%s",a[i];
		if(i<length(a)) printf " ";
	}
	printf "\n"
	}'\'' | column'

alias path='echo -e ${PATH//:/\\n}'

alias home='cd ~'
alias desktop='cd ~/Desktop'
alias mydocs='cd ~/Documents'
alias docs='cd ~/Documents'
alias music='cd ~/Music'
alias videos='cd ~/Videos'
alias downloads='cd ~/Downloads'

alias mplayer='mplayer -quiet -framedrop $*'


# COLOR DEFINES
####################

red='\e[0;31m'
RED='\e[1;31m'
green='\e[0;32m'
GREEN='\e[1;32m'
yellow='\e[0;33m'
YELLOW='\e[1;33m'
blue='\e[0;34m'
BLUE='\e[1;34m'
purple='\e[0;35m'
PURPLE='\e[1;35m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
white='\e[0;37m'
WHITE='\e[1;37m'
black='\e[0;30m'
BLACK='\e[1;30m'
NC='\e[0m'              # No Color

# PR = Primary Color
# SC = Secondary Color
# Mmmm, Minty
PR=$YELLOW
SC=$GREEN

# FUNCTIONS
####################

function _greet()
{
	hour=`date +'%H'`
	if [ $hour -lt 12 ]; then
		echo "Good morning"
	elif [ $hour -lt 18 ]; then
		echo "Good day"
	else
		echo "Good evening"
	fi
}

# WELCOME SCREEN
####################

username=`whoami`
echo -e ${SC}`_greet` ${PR}`~/bin/titlecase $username`${SC}, welcome to ${PR}`hostname`
echo -e ${SC}`cat /etc/issue.net` `uname -omp`
echo -e ${PR}`hostname`\'s ${SC}IP address is ${PR}`hostname -I`
echo -e ${PR}Router\'s${SC} IP address is ${PR}`~/bin/ipaddress`
echo -e ${SC}Uptime for ${PR}`hostname`${SC} is ${PR}`uptime | awk /'up/ {print $3}'`
echo
titlecase

Code: Select all

#!/usr/bin/python

from sys import argv

if len(argv) == 1 or argv[1].lower() in ["--help", "--h", "-h", "-help"]:
	from os.path import basename
	print "Prints the passed arguements converted to title case."
	print "Usage: %s <string> ..."%(basename(argv[0]))
	exit()

for arg in argv[1:]:
	print arg.title(),
ipaddress

Code: Select all

#!/usr/bin/python

"""
	About: A simple script to fetch an IP address from a remote host
	Version: 1.1
	
	HISTORY
	--------------------------------------------------------------------
	Version 1.1 - 06/25/2012
	 * Fixed hanging on non-responsive hosts.
	 * Removed several non-responsive hosts from host list.
	 * Added option to verify hosts are still working.
	
	Version 1.0 - 05/06/2012
"""

from urllib2 import urlopen
from re import findall
from os.path import isfile, dirname, join, basename
from time import time
from sys import exit, argv

########################################################################
# Config section

# These hosts provide a simple plain text or minimal HTML
# page with your IP address
hosts = [
	"http://www.formyip.com/",
	"http://checkip.dyndns.org/",
	"http://www.cmyip.com/",
	"http://www.viewmyipaddress.com/",
	"http://cfaj.freeshell.org/ipaddr.cgi",
	"https://secure.informaction.com/ipecho/",
	"http://icanhazip.com/",
	"http://ipecho.net/plain",
	"http://smart-ip.net/myip",
]

cache_update = 3600
cache_name = "ipaddr_cache"

# End Config
########################################################################

cache_name = join(dirname(argv[0]), cache_name)
cache_stale = False
cache_exists = False
help = False
verify=False

# Fetch IP from remote host
def fetchIP(host,data=None,timeout=10):
	try:
		r = urlopen(host,data,timeout)
		h = r.read()
		r.close()
		return findall("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", h)[-1]
	except:
		return None

# Parse Options
for option in argv[1:]:
	opt = option.lower()
	if opt == "--stale":
		cache_stale = True
	elif opt[:7] == "--host=":
		host = option[7:]
		cache_stale = True
	elif opt == "--help":
		help = True
	elif opt == "--verify":
		verify = True
		cache_stale = True

# Print help and exit
if help:
	print "Usage: %s [options]"%(basename(argv[0]))
	print "Options:"
	print "  --host=<hostURL>\tFetch IP address from hostURL."
	print "  --stale\t\tDon't use cached IP address."
	print "  --verify\t\tVerify all hosts are still working."
	print "  --help\t\tThis message"
	exit()


# Check if a cache file exists
if not isfile(cache_name):
	cache_exists = False
else:
	cache_exists = True
	
# If the cache exists use it unless it's stale
if cache_exists and not cache_stale:
	d = open(cache_name,"r").readlines()	
	if int(d[0]) > time() - cache_update:
		print d[1]
	else:
		cache_stale = True

h = False
# Cache is stale or doesn't exist, lets get the IP
if not cache_exists or cache_stale:
	while True:
		if not hosts:
			print "Exhausted all IP Address Servers"
			break
		
		if not h and verify:
			print "IP ADDRESS\tTIME\tHOST"
			h = True
		
		host = hosts.pop(int(time())%len(hosts))
		c = time()
		ip = fetchIP(host)
		c = time() - c
		if ip:
			open(cache_name, "w").write("%d\n%s"%(time(),ip))
			if not verify:
				print ip
				break
			else:
				print "%s\t%0.2f\t%s"%(ip,c,host)
		else:
			if verify:
				print "Failed\t\t%0.2f\t%s"%(c,host)
			continue
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 3 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
vincezd

Re: What's in your .bashrc?

Post by vincezd »

Hello,
Yeah let's do that !

You know nautilus-open-terminal right ? This is the other-way, how to open the current directory in nautilus with a keyboard shortcut :

Code: Select all

bind -x '"\C-x\C-n":nautilus $(pwd)  1>/dev/null 2>/dev/null &' #Ctrl-x-n
# and when I ctrl-z vim, to quickly have it back :
bind -x '"\C-x\C-a":fg %vim'
Quickly translate one word from english to french :

Code: Select all

enfr() {
    elinks http://www.wordreference.com/enfr/$1 # you can use fren, esfr, fres, ende, deen, ...
}
Intelligent CD :
give some keywords. We'll go automatically to a directory that fetches. Prints a result list if many.
(don't do it in the home ...)
Doesn't work so good / not so useful but saved me some time. I would suggest using cdargs instead (or sthg better ?)

Code: Select all

icd(){
    arg=''
    # while we have arguments, append them with a wildcard in between
    while [ $# -gt '0' ] ; do
        arg=$arg*$1
        # note that we didn't add a * at the end. The last key-word must fetch the end of the last directory ... exple :
        # "icd foo bar" will fetch ./aaa/foo/bbb/bar but not ./aaa/foo/bbb/bar2
        shift
    done
    tmpfile=/tmp/icd.txt
    find . -type d -iwholename "$arg" > $tmpfile
    nbrlignes=$(wc --lines $tmpfile | grep -o [0-9])

    if [ $nbrlignes -gt '1' ] ; then
        cecho $v "Many matching directories :"
        cat $tmpfile
    else
        if [ $nbrlignes -gt '0' ] ; then
            cd $(cat $tmpfile)
        else echo "rien trouve"
        fi
    fi
    # known issue : you must not have spaces in folder name :/
}
The most useful of all : wrapper around find & music player.
For example, I'm used to downloading a lot of music. At a point, I want to listen what I downloaded today. I just go to my music directory and run "mfind -c 1" to see what I have and then I add "-p" to play.

It can also be used to simply look for a file.

Usage : "mfind indus joke -c 1" will look for all files created today having "indus" and "joke" in their pathname; adding "-p" will play them.

Code: Select all

mfind () {
    play=0
    ma_playlist=ma_playlist$(date '+%T') #so that you can run multiple times the script in the same dir
    if [ $# -eq '0' ] ; then
        echo "This script is a wrapper around find."
        echo "usage : mfind key_word other_key_word"
        echo "option -p : play media files with mplayer mplayer"
        echo "option -c n : list files which were modified within n days." 
        # you can give options in any order : mfind -p foo bar -c 1 or mfind -c 1 fooo bar -p
        return
    fi
    
    arg=''; n=''; ctime=''
    while [ $# -gt '0' ] ; do
        if [ $1 = "-p" ] ; then
            echo play \!
            play=1
        else 
            if [ $1 = "-c" ] ; then
                ctime='-ctime'
                shift
                if [ $# -eq '0' ] ; then
                    echo You must specify a number of days \!
                    return
                fi
                n="-$1"
            else
                arg=$arg*$1 # append key words with a wildcard in between
            fi
        fi
        shift
    done

    arg=$arg'*'
    #-iname only searches in the file name, whereas
    #-iwholename in the path
    find . $ctime $n -iwholename "$arg" |sort > $ma_playlist
    cat $ma_playlist
    if [ "$play" -eq "1" ] ; then
        mplayer -playlist $ma_playlist
    fi
    rm $ma_playlist
    # Known issue : as it creates a file in the working directory, you must have write access.
}
From there, and it's terribly useful too, when I want a simple shuffle of all media files :

Code: Select all

mshuffle() {
    REP=
    find $@ ./ -iname "*.mp3" -o -iname "*.wma" -o -iname "*.mp4" -o -iname "*.wmv" -o -iname "*.ogg" -o -iname "*.m4a" -o -iname "*.wav" \
-o -iname "*flv" >${REP}ma_playlist
    
    mplayer -shuffle -playlist ${REP}ma_playlist
    rm ${REP}ma_playlist
}
We could improve it a lot but why not use a real music player then ? :p
cowsquad

Re: What's in your .bashrc?

Post by cowsquad »

Wow that is helpful

Sent from my Galaxy Nexus
dajare

Re: What's in your .bashrc?

Post by dajare »

Jamesc359 wrote:... I've added a few things to my .bashrc file to make life a little easier. Of course I added a few helper scripts too. :-) ...
Genius -- thanks for posting this!

I've supplemented it with some info I found about altering the bash system prompt and I'm a much happier person just now. (Doesn't take much. ;) )

Putting the "user @ hostname + current dir" info in the terminal's title bar was especially useful (the example under "Xterm fun"). Clearing that out of the pre-prompt area makes for a much more sane command line!
defcon

Re: What's in your .bashrc?

Post by defcon »

In my .bashrc?
Hm, nothing special ...

Code: Select all

# extract - archive extractor
# usage: extract <file>
extract ()
{
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2)   tar xjf $1   ;;
      *.tar.gz)    tar xzf $1   ;;
      *.bz2)       bunzip2 $1   ;;
      *.rar)       rar 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 extract()" ;;
    esac
  else
    echo "'$1' is not a valid file"
  fi
}
vincezd

Re: What's in your .bashrc?

Post by vincezd »

Very, very handy !
sagirfahmid3

Re: What's in your .bashrc?

Post by sagirfahmid3 »

I like defcon's bashrc lol. The extraction one ftw!
jralabate

Re: What's in your .bashrc?

Post by jralabate »

Edit: Removed

Sent from my NS4G powered by AOKP ICS
Habitual

Re: What's in your .bashrc?

Post by Habitual »

Not much to see here except retro DOS-style linux prompt - C:\home\jj>

Code: Select all

DOS='C:${PWD//\//\\\}>'
LOAD=$(/usr/bin/w | /usr/bin/head -1)
PS1="\[\033[00m\]\[\033[01;31m\]\n\[\033[00m\]\[\033[01;39m\]$DOS\[\033[00m\]" # C:\home\jj> prompt.

export GREP_OPTIONS='--color=auto' GREP_COLOR='7;31'

export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;37m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

EDITOR='/usr/bin/vi'
export EDITOR
export LESS='FiX'
export GPGKEY=86F28105
source /home/jj/.aliases
source /home/jj/.c9ssh
alias reload='clear && source ~/.bashrc'

alias myweb="ssh -i /home/jj/.ssh/newbox_rsa secret@xx.xxx.224.45 -p 9901"
alias mydb="ssh -i /home/jj/.ssh/newbox_rsa secret@xxx.xx.224.45 -p 9902"
alias btrs="ssh -qi /home/jj/.ssh/c9/moose_rsa noneofyourbusiness@bournetoraiseshell.com"

export EC2_HOME=/home/jj/bin/ec2
export EC2_PRIVATE_KEY=/home/jj/.ssh/c9/pk-noneofyourbusiness.pem
export EC2_CERT=/home/jj/.ssh/c9/cert-noneofyourbusiness.pem
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-sun-1.6.0/jre


alias fixrpm="sudo rpm --rebuilddb"
alias remm="remind -n  ~/.reminders  | sort | head -12 | cut -d '/' -f1 --complement"
source /home/jj/.functions

export BROWSER=firefox
alias manb="man -H"
HISTCONTROL=ignoredups:ignorespace
HISTSIZE=30000
HISTFILESIZE=30000 
/home/jj/bin/stamp.sh
alias ping="ping -c2 -w1"
alias cleanhist="history | sed 's/^[ 0-9]* //'"
echo $(/usr/share/conkyforecast/conkyForecast.py --location=USOH1096 -d HT --imperial) at $(/usr/share/conkyforecast/conkyForecast.py --location=USOH1096 -d HM) Humidity
PS1 and /home/jj/bin/stamp.sh and the conkyForecast bit gives me
C:\home\jj>
Tue Jul 10, 2012 - 7:29:34 AM EDT
59°F at 90% Humidity

prompt every time.
Locked

Return to “Scripts & Bash”