code

Its all just ones and zeroes isn't it? 
Filed under

bash

 

Writing a Bash script that knows its own location

I wrote a small bash script the other day, on Ubuntu, to launch a java program in a jar file.  My first attempt worked, but it only worked if you invoked the script from the folder the script was in, but if it was invoked from any other folder, it would fail, because it was referencing the jar file with a relative path, and that path was relative of the location the script was invoked from, not the location it resided in.

Here's an example script:

#!/bin/bash
LSOF=$(lsof -p $$ | grep -E "/"$(basename $0)"$")
MY_PATH=$(echo $LSOF | sed -r s/'^([^\/]+)\/'/'\/'/1 2>/dev/null)
MY_ROOT=$(dirname $MY_PATH)
java -cp $MY_ROOT/../target/yourjar-1.0-SNAPSHOT-jar-with-dependencies.jar com.acme.YourClass

I did find one edge case where this doesn't work.. If the script is in a folder with the same name as the script, it gets messed up.

Filed under  //   bash   howto   java   ubuntu  

Comments [0]