Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script fil
The best answer for this question was answered here:
Getting the source directory of a Bash script from within
And it is:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
One-liner which will give you the full directory name of the script no matter where it is being called from.
To understand how it works you can execute the following script:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink
with option -f
. Works when the script is called by an absolute as well as by a relative path.
For bash, sh, ksh:
#!/bin/bash
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH
For tcsh, csh:
#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH
See also: https://stackoverflow.com/a/246128/59087
Assuming you're using bash
#!/bin/bash
current_dir=$(pwd)
script_dir=$(dirname $0)
echo $current_dir
echo $script_dir
This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from /
with the script in /home/mez/
, it outputs
/
/home/mez
Remember, when assigning variables from the output of a command, wrap the command in $(
and )
- or you won't get the desired output.
As theMarko suggests:
BASEDIR=$(dirname $0)
echo $BASEDIR
This works unless you execute the script from the same directory where the script resides, in which case you get a value of '.'
To get around that issue use:
current_dir=$(pwd)
script_dir=$(dirname $0)
if [ $script_dir = '.' ]
then
script_dir="$current_dir"
fi
You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue.