pwd command with shell script
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 di开发者_如何学运维rectory path?
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.
May be this can help you.
var_path=$PWD
echo $var_path
Try this one, it should come close to what you want:
var_path=`dirname "$0"`
Please see BashFAQ/028.
This topic comes up frequently. This answer covers not only the expression used above ("configuration files"), but also several variant situations. If you've been directed here, please read this entire answer before dismissing it.
This is a complex question because there's no single right answer to it. Even worse: it's not possible to find the location reliably in 100% of all cases. All ways of finding a script's location depend on the name of the script, as seen in the predefined variable $0. But providing the script name in $0 is only a (very common) convention, not a requirement.
. . .
Generally, storing data files in the same directory as their programs is a bad practise. The Unix file system layout assumes that files in one place (e.g. /bin) are executable programs, while files in another place (e.g. /etc) are data files.
Read the complete page for lots more good information.
精彩评论