Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix shell script find out which directory the script file resides?

Tags:

shell

unix

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?

like image 669
William Yeung Avatar asked Oct 28 '08 08:10

William Yeung


People also ask

How do I find the path of a script in Unix?

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.

How do I find the directory of a script?

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).

How do I find the path of a file in shell?

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/.


2 Answers

In Bash, you should get what you need like this:

#!/usr/bin/env bash  BASEDIR=$(dirname "$0") echo "$BASEDIR" 
like image 177
TheMarko Avatar answered Sep 24 '22 02:09

TheMarko


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

like image 29
al. Avatar answered Sep 24 '22 02:09

al.