9 insane bash functions


Over the weekend I got into some bash functions.
Paste these into your .bashrc file
1. Command line wiki query
function wiki () {

COLUMNS=`tput cols`
dig +short txt “`echo $@`”.wp.dg.cx | sed -e ‘s/” “//g’ -e ‘s/^”//g’ -e ‘s/”$//g’ -e ‘s/ http:/\n\nhttp:/’ | fmt -w $COLUMNS
2. Disk Usage with human readable formatting
#disk usage formatted
function duf {
du -sk "$@" | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done

3. Directory sizes
#dirsize - finds directory sizes and lists them for the current directory
dirsize () {
du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
egrep '^ *[0-9.]*[MG]' | sort -n > /tmp/list
egrep '^ *[0-9.]*M' /tmp/list
egrep '^ *[0-9.]*G' /tmp/list
rm -rf /tmp/list

4. Power extract function
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()" ;;
echo "'$1' is not a valid file"

6. Network Information
#netinfo - shows network information for your system
netinfo ()
echo "--------------- Network Information ---------------"
/sbin/ifconfig | awk /'inet addr/ {print $2}'
/sbin/ifconfig | awk /'Bcast/ {print $3}'
/sbin/ifconfig | awk /'inet addr/ {print $4}'
/sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
myip=`lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g' `
echo "${myip}"
echo "---------------------------------------------------"

7. Translate from commandline
#Translate a Word  - USAGE: translate house spanish  # See dictionary.com for available languages (there are many).
translate ()
TRANSLATED=`lynx -dump "http://dictionary.reference.com/browse/${1}" | grep -i -m 1 -w "${2}:" | sed 's/^[ \t]*//;s/[ \t]*$//'`
if [[ ${#TRANSLATED} != 0 ]] ;then
echo "\"${1}\" in ${TRANSLATED}"
echo "Sorry, I can not translate \"${1}\" to ${2}"

8. Define a word
# Define a word - USAGE: define dog
define ()
lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}&btnG=Google+Search" | grep -m 3 -w "*"  | sed 's/;/ -/g' | cut -d- -f1 > /tmp/templookup.txt
if [[ -s  /tmp/templookup.txt ]] ;then
until ! read response
echo "${response}"
done < /tmp/templookup.txt
echo "Sorry $USER, I can't find the term \"${1} \""
\rm -f /tmp/templookup.txt

9. Simple Clock
# clock - A bash clock that can run in your terminal window.
clock ()
while true;do clear;echo "===========";date +"%r";echo "===========";sleep 1;done

MORE functions can be found here

The cool cd terminal hack

No Comments

Method One: Navigate up the directory using “..n”
In the example below, ..4 is used to go up 4 directory level, ..3 to go up 3 directory level, ..2 to go up 2 directory level.
Add the following alias to your ~/.bashrc and re-login.
alias ..=”cd ..”
alias ..2=”cd ../..”
alias ..3=”cd ../../..”
alias ..4=”cd ../../../..”
alias ..5=”cd ../../../../..”
Method Two: Navigate up the directory using only dots
In the example below, ….. (five dots) is used to go up 4 directory level. Typing 5 dots to go up 4 directory structure is really easy to remember, as when you type the first two dots, you are thinking “going up one directory”, after that every additional dot, is to go one level up. So, use …. (four dots) to go up 3 directory level and .. (two dots) to go up 1 directory level.
Add the following alias to your ~/.bashrc and re-login for the ….. (five dots) to work properly.
alias ..=”cd ..”
alias …=”cd ../..”
alias ….=”cd ../../..”
alias …..=”cd ../../../..”
alias ……=”cd ../../../../..”
THANKS: Linux Tips & The Geek Stuff
(For two other methods, check out The Geek Stuff, and while you at it, read the best posting yet on RTFM)

Categories: Ubuntu

Tags: ,

A Wikipedia query in your terminal

No Comments

Open ~/.bashrc with your favourite editor.

gedit ~/.bashrc

Place the following to the end:

function wiki () {
COLUMNS=`tput cols`
dig +short txt "`echo $@`".wp.dg.cx | sed -e 's/" "//g' -e 's/^"//g' -e 's/"$//g' -e 's/ http:/\n\nhttp:/' | fmt -w $COLUMNS

Reset your bash terminal: $bash
To invoke type wiki <subject-of-your-query>. It will return some interesting and useful information.

Categories: Ubuntu

Tags: ,

Smart autocompletion of BASH commands

No Comments

I have been looking for a way to favourite my commands. Turning on Bash Smart autocompletion is a start. I found this posting at Ubuntu Blog:

The Bash shell has this sweet feature where you can use the TAB key to auto-complete certain things. For example, when I am in my home directory, the following command:
$cd Do[TAB-key]
will automatically yield:
$cd Documents
If you are an absolute novice, like I was, not so long ago, discovering tab completion in the terminal can make you go “Wow!”. Wait till you hear the rest now 🙂
Though you can use the TAB key to complete the names of files and directories, by default the completion is pretty “dumb”. If you have already typed $cd D you would expect that the tab key would cause only the directory names to be completed, but if I try it on my machine, the tab completion tool uses filenames too.
Now, don’t despair! There is now a smart bash tab completion trick you can use. Smart completion even complete the arguments to commands!!
To enable smart completion, edit your /etc/bash.bashrc file. Uncomment the following lines, by removing the # in the beginning of the lines:
#if [ -f /etc/bash_completion ]; then
# . /etc/bash_completion

Now you can use tab completion to power your way through commands.
You can even extend bash smart completion to your own favourite commands by using /etc/bash_completion, the “complete” utility and /etc/bash_completion.d . Explaining the nitty-gritty is beyond me. I refer you to the Debian Administration gurus for more information regarding smarter bash completion.

Thanks Carthik, I do believe this is the solution. First turn on smart autocompletion, check to see if your favourite commands autocomplete, and if not, then create a file containing these commands using the link provided.
UPDATE: Working with history in Bash

Categories: CLI Ubuntu

Tags: ,

Favourite your top Ubuntu commands and add fixkey

1 Comment

[PLEASE SEE Better PPA Fixkey Method the below is for informational purposes only.]
In Fix Software Sources Bad Behaviour we reported two methods for accomplishing the same task of fixing keys. The first, involved manually entering two lines in a terminal. The second involved one entry. Now there is a third faster method. Aliasing.
ICE20.com describes aliasing in BASH this way:
Many of us use certain commands over and over again, or we have preferred combinations of options which we always give to certain commands. We can create shortcuts to these commands by giving them an alias in our ~/.bashrc file. The format is:

alias new_name=’command -options’

There are some examples provided at the above site, but the one we want to create is this:
alias fixkey=’sudo apt-key adv –recv-keys –keyserver keyserver.ubuntu.com’
Which will execute a command string when you type fixkey.
1. All you have to do is backup your ~/.bashrc file
cp .bashrc .bashrc.bak
2. then open it in a text editor
gedit ~/.bashrc
3. Scroll down to the relevant section.
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

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

4. Uncomment so it looks like this
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases

5 Save and exit.
Bash documentation recommends creating a separate file for aliases like this.
6. Create the  ~/.bash_aliases file
gedit ~/.bash_aliases
7. Enter the following code
alias fixkey=’sudo apt-key adv –recv-keys –keyserver keyserver.ubuntu.com’
8. Save and exit.
9. Refresh bash. by either logging out, closing the terminal or entering $ bash
10 To fix an errant key, using fixkey. Open Terminal


WARNING: I  tried the above first leaving the sudo command out and entering it directly in .bashrc expecting that one should be able to simply sudo fixkey in this instance, but this merely turns up a “command not found” dialogue and so I included sudo  in the command string in order for it to execute. This might not be the case with the .bash_aliases file. Any advice on this would be welcome. please see Better PPA Fixkey Method
NOTE: I don’t recommend going off and aliasing everything you do, as you terminal will quickly begin to resemble a unique creature which might bork when you install a new piece of software with the same command structure. (How exactly does this problem of potential commandline scripting conflict get resolved? For example, the above is substantially similar to the following posting at Commandlinefu. Depending on whether your starting point is the ‘addition’ of a key, or ‘fixing’ a key after the fact. Of course both fixkey and launchpadkey can coexist) Rather, I suggest we share commands at places like Commandlinefu or Ubuntu Forums and see if there is any agreement within the broader Ubuntu Community at what to do about reducing relatively complex or time-consuming CLI tasks into easy to remember, attractive or familiar commands. In fact creating more human, or themed commands using the aliasing capabilities of bash, could be the next frontier. I imagine the day when we will be sharing and exchanging CLI matrices or schemas as easily as trying on a new hat or pair of shoes. If the shoe fits, wear it, if not, give it away. – DRL

SEE Environment Variables

Categories: CLI PPA Ubuntu

Tags: ,