Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pwd command with shell script

Tags:

shell

I am calling a script as below


directory path : /user/local/script/print_path.sh

var_path=`pwd`
echo $var_path

The above script is calling as below directory path : /user/local/callPscript/call.sh

`/user/local/script/print_path.sh`

I want the out put as below :

/user/local/script/

But it gives the output :

/user/local/callPscript/

i.e. the pocation of the script is called. How can I make it to the scripts home directory path?

like image 919
Arunjith Avatar asked Mar 10 '11 07:03

Arunjith


2 Answers

After some weeks of Bash programming, this has emerged as the standard solution:

directory=$(dirname -- $(readlink -fn -- "$0"))

$0 is the relative path to the script, readlink -f resolves that into an absolute path, and dirname strips the script filename from the end of the path.

A safer variant based on the completely safe find:

directoryx="$(dirname -- $(readlink -fn -- "$0"; echo x))"
directory="${directoryx%x}"

This should be safe with any filename - $() structures remove newlines at the end of the string, which is the reason for the x at the end.

like image 112
l0b0 Avatar answered Oct 06 '22 00:10

l0b0


May be this can help you.

var_path=$PWD  
echo $var_path
like image 21
cdummy Avatar answered Oct 05 '22 23:10

cdummy