Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Finding a bash script's full path

Posted on 2006-11-08
4
Medium Priority
?
461 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 85

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 85

Accepted Solution

by:
ozo earned 1000 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

877 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