Find the Absolute Path / Directory of a Bash Script

Recently, while writing a script I needed to know what directory the script resides in from within the script. A few google searches later I found a couple solutions. Jotting them down here for fellow googlers. 🙂

Solution 1:

ABSPATH="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
DIRPATH=`dirname "$ABSPATH"`

Solution 2:

LSOF=$(lsof -p $$ | grep -E "/"$(basename $0)"$")
ABSPATH=$(echo $LSOF | sed -r s/'^([^\/]+)\/'/'\/'/1 2>/dev/null)
DIRPATH=$(dirname $ABSPATH)

I ended up using Solution 1, because its not dependent on any external command.

Easily and Uniformly Indent XML Files using xmllint and a small hack

xmllint has the --format option using which you can indent XML files. However the indentation doesn’t always work. For eg, it refuses to indent a file in the below format

<?xml version="1.0"?>
<status>
  <xyz arg1="1">
 a 
</xyz>
  <abc arg2="2">
 p
 </abc>
  <pqr arg3="3" arg4="a phrase">
 x
 </pqr>
</status>

To make it indent all well-formed files uniformly, use this command: (Assuming the file you want to indent is called test.xml)

cat test.xml | tr '\n' ' ' | xmllint --format - > /tmp/test.xml; mv /tmp/test.xml test.xml

The indented output will look like:

<?xml version="1.0"?>
<status>
  <xyz arg1="1"> a </xyz>
  <abc arg2="2"> p </abc>
  <pqr arg3="3" arg4="a phrase"> x </pqr>
</status>

Parse Simple XML Files using Bash – Extract Name Value Pairs and Attributes

I have written up a simple routine parseXML to parse simple XML files to extract unique name values pairs and their attributes. The script extracts all xml tags of the format <abc arg1="hello">xyz</abc> and dynamically creates bash variables which hold values of the attributes as well as the elements. This is a good solution, if you don’t wish to use xpath for some simple xml files. However you will need xmllint installed on your system to use the script. Here’s a sample script which uses the parseXML function Continue reading

Makefile Tricks: Arithmetic – Addition, Subtraction, Multiplication, Division, Modulo, Comparison

While working on a project, I needed to do some calculations inside a Makefile. Took me sometime to figure out how, hence jotting it down. Here’s a sample makefile where I have show examples of standard calculations.

NUMBER1 := 10
NUMBER2 := 5

#Addition
ADD := $(shell echo ${NUMBER1}+${NUMBER2} | bc)

#Subtraction
SUBTRACT := $(shell echo ${NUMBER1}-${NUMBER2} | bc)

#Multiplication
MULTIPLY := $(shell echo ${NUMBER1}*${NUMBER2} | bc)

#Division
DIVIDE := $(shell echo ${NUMBER1}/${NUMBER2} | bc)

#Division (Floating Point)
DIVIDEF := $(shell echo "scale=3; ${NUMBER2}/${NUMBER1}" | bc)

#Modulo
MODULO := $(shell echo ${NUMBER1}%${NUMBER2} | bc)

#Comparison Greater Than
COMPARISON1 := $(shell echo ${NUMBER1}\>=${NUMBER2} | bc)

#Comparison Smaller Than
COMPARISON2 := $(shell echo ${NUMBER2}\<=${NUMBER2} | bc)

all:
  @echo Addition ${ADD}
  @echo Subtraction ${SUBTRACT}
  @echo Multiplication ${MULTIPLY}
  @echo Division ${DIVIDE}
  @echo Division  - Floating Point ${DIVIDEF}
  @echo Modulo ${MODULO}
  @echo Comparison Greater Than ${COMPARISON1}
  @echo Comparison Smaller Than ${COMPARISON2}

Besides what is shown above, you can use anything that bc supports like boolean operators, relational expressions etc.

To execute the above code, copy the code to a file and name the file Makefile. Run the make command in the directory you created the Makefile in. You should see the following output.

@$ make
Addition 15
Subtraction 5
Multiplication 50
Division 2
Division - Floating Point .500
Modulo 0
Comparison Greater Than 1
Comparison Smaller Than 1

Hope this helps.

Highlight and Search – Google Search from Any Ubuntu Linux Application

Some time ago, I wrote a post to show how to modify terminator to enable easy google searching. However I have trumped myself and have an even better solution now. Google Search from any application. Modus Operandi is: Highlight Text => Press Key Combination => Script picks up the query from the clipboard => Formats the query and opens the URL in your defualt browser.

Lets start with the script. Copy-Paste the below code into a file (Lets name it google_search).

#!/bin/bash
QUERY=`xclip -o | tr ' ' '+'`  #sanitize the query, change spaces to the plus sign
QUERY='"'$QUERY'"'    #put quotes around the query, exact search

if [ -x ~/bin/open_browser.sh ]; then
  open_browser.sh http://www.google.com/webhp?hl=en#hl=en\&q=$QUERY
else
  x-www-browser http://www.google.com/webhp?hl=en#hl=en\&q=$QUERY
fi

Copy the file to the bin directory under your home directory. Make the script executable.

cp google_search ~/bin
chmod +x ~/bin/google_search

Now lets take care of a few dependencies.

Install xclip. This utility is used to interact with the clipboard.

sudo aptitude install xclip

Update x-www-browser. See this tutorial for more instructions.

sudo update-alternatives --config x-www-browser

Now lets create a keyboard shortcut for the script we saved earlier.

Tutorial for KDE Users
Tutorial for Gnome Users

Thats it. Now you can highlight any text and press the keyboard shortcut you created in the last step and a google search for the selected phrase will open up in your default browser.

This script also supports the open_browser.sh script. Look here for more info.
When you press the keyboard combination, the browser may or may not become the active window. That depends on the focus model. However if you check your browser, the google search should be open in a new tab

Setup Default Browser for Non-GUI Applications in Ubuntu Linux (x-www-browser)

KDE and Gnome provide GUI to setup the default browser in Ubuntu. However for the default browser settings to be accessible in bash scripts, a further step is required. That is to setup x-www-browser.

Set the default x-www-browser using the update-alternatives command.

sudo update-alternatives --config x-www-browser

Enter the number corresponding to the browser you want as your default browser.

default-x-www-browser

Custom Keyboard Shortcuts in KDE

While writing a post, I wanted to link a simple tutorial for creating custom keyboard shortcuts in KDE. However I couldn’t find a single tutorial! So here is one:

  1. Hit Alt+F2 (or your custom shortcut for the Run Dialog)
  2. Enter System Settings to start up the tool
  3. Double Click on Shortcuts and Gestures under Application appearance and Behavior
  4. Click on Edit towards the bottom of the screen which opens a popup menu
  5. Navigate to New => Global Shorcut => Command/URL and left click on Command/URL
  6. Change the default name New Action to anything of your choice
  7. Go to the Trigger tab and click on None and press a key combination of your choice
  8. Go to the Action tab and select/enter the path to the script/executable

Pictures speak louder than words..

Custom Key Bindings / Keyboard Shortcuts in Bash

Bash is so powerful that you can keep digging and finding out newer secrets all the time. We already use bash keyboard bindings – Ctrl d to exit the terminal, Ctrl r for reverse search and so on. Now won’t it be convenient if you could assign keyboard bindings to commands of your choice, to execute them quickly or just to insert lengthy commands which you use repeatedly with subtle changes. Lets look at an example. Continue reading