Solved

Finding a bash script's full path

Posted on 2006-11-08
4
436 Views
Last Modified: 2008-02-01
I'm wondering if any experts in bash could offer me a better way to computer the full pathname to $0 in a script.

Specifically, I need to know the path the script is in, so it can do it's work in that (and only in that) directory.

Right now, I'm using the following four lines:
DIR="$PWD/`dirname $0`"      #Compute a full path name to this script
DIR=${DIR%.}            #Strip off trailing period
DIR=${DIR%\/}            #Strip off trailing slash
DIR=${DIR/\/\/\//\/}#Reduce any initial /// to /

The first line creates a full path, but it may have some strangeness (e.g., a trailing period if the bash script is launched directly from the directory, the odd trailing "/" in some cases, and the problem of "///home/xyz/abc", which $PWD can produce.

This four-line sequence works; I'm interesting in finding out of there any easier way to do this for my future bash scripts
0
Comment
Question by:CAOgdin
  • 2
  • 2
4 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 17902522
which $0
0
 

Author Comment

by:CAOgdin
ID: 17902559
Nice one.  I wonder how it missed that command.

Still not quite there, though.  I need it without the name of the script...just the path to the script itself.

It returns /home/xyz/abc/test for a script named "test."  I need just /home/xyz/abc
0
 
LVL 84

Accepted Solution

by:
ozo earned 250 total points
ID: 17902608
dirname `which $0`
0
 

Author Comment

by:CAOgdin
ID: 17902665
Slick!  I'm impressed (and it urges me on to learn more about bash).

Thanks.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now