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?
How do I find out the current directory location and shell script directory location in Bash running on Linux or Unix like operating systems? basename command – Display filename portion of pathname. dirname command – Display directory portion of pathname.
pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).
2.1. To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.
In Bash, you should get what you need like this:
#!/usr/bin/env bash BASEDIR=$(dirname "$0") echo "$BASEDIR"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With