PDA

View Full Version : Find a shell script's location within the script?


maybeway36
April 12th, 2008, 09:48 AM
Is there a way from inside a shell script to find out where the script is located (which folder it is in?)

chewearn
April 12th, 2008, 09:57 AM
pwd

LaRoza
April 12th, 2008, 10:02 AM
pwd

That will print the working directory, not the scripts location.

ghostdog74
April 12th, 2008, 12:44 PM
Is there a way from inside a shell script to find out where the script is located (which folder it is in?)
you can try $0
eg

#!/bin/bash
scriptpath=$0
case $scriptpath in
./*) echo `pwd` ;;
* ) dirname $scriptpath
esac

stroyan
April 12th, 2008, 01:36 PM
Bash reports paths to the files it is running from in the BASH_SOURCE array.
You may want to use readlink to find the real path through symbolic links.

script_dir="$(dirname "$(readlink -f ${BASH_SOURCE[0]})")"

bennit
January 25th, 2009, 03:42 PM
cd `dirname`; pwd

mangup
August 31st, 2009, 03:31 PM
This one also works, though it's a bit lengthy:

# Function returns the full path to the current script.
# Example:
# tmp=`currentscriptpath`
# echo "path to current script is: "$tmp
currentscriptpath()
{
local fullpath=`echo "$(readlink -f $0)"`
local fullpath_length=`echo ${#fullpath}`
local scriptname="$(basename $0)"
local scriptname_length=`echo ${#scriptname}`
local result_length=`echo $fullpath_length - $scriptname_length - 1 | bc`
local result=`echo $fullpath | head -c $result_length`
echo $result
}