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 file resides?
In bash you should get what you need like this:
#!/bin/bash
BASEDIR=$(dirname $0)
echo $BASEDIR
Assuming you're using bash
#!/bin/bash
current_dir=$(pwd)
script_dir=$(dirname $0)
echo $current_dir
echo $script_dir
This script, when ran, should print the directory that you're in, and then the directory the script is in, for example, when calling it from / (the script is in /home/mez/), it outputs
/
/home/mez
Remember, when assigning variables from the output of a command, wrap the command in $( and ) - or you'll not get the desired output. `
I'm not sure how to do it, but neither of the previous answers work. This is because $0 is the command as called. If you call the script foo like this './foo', then $0 = ./foo, not /path/to/foo like you want.
Have a look at http://fritzthomas.com/open-source/linux/384-how-to-get-the-absolute-path-within-the-running-bash-script
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.
Here a slightly modified copy of the solution in case the other post vanishes....
This is 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
Almost the same 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
If you're using bash....
#!/bin/bash
pushd $(dirname "${0}") > /dev/null
basedir=$(pwd -L)
# Use "pwd -P" for the path without links. man bash for more info.
popd > /dev/null
echo "${basedir}"
This checks if directory exists and is writable
if [ -d "$Directory" -a -w "$Directory" ]
then
#Statements
fi
-Muralikrishna.B