如何检测我运行shell脚本的当前目录?

时间:2021-12-31 20:36:18

How may I detect the name of the directory (or better yet the entire path) in which my shell script is run?

我如何检测运行shell脚本的目录名称(或者更好的是整个路径)?

4 个解决方案

#1


19  

what shell? What operating system?

什么壳?什么操作系统?

For starters try

首先尝试

man pwd
$PWD

#2


15  

This, I believe, is the most portable way:

我认为,这是最便携的方式:

dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

#3


3  

This is not as trivial as it looks like. Check out this question and this

这并不像它看起来那么微不足道。看看这个问题吧

#4


0  

alternative method

替代方法

pid=$$
path=$(ps -eo pid,args| awk -vp=$pid '$1~p{print $3}')
case "$path" in
    ./* ) pwd;;
    * ) echo $path;;
esac

#1


19  

what shell? What operating system?

什么壳?什么操作系统?

For starters try

首先尝试

man pwd
$PWD

#2


15  

This, I believe, is the most portable way:

我认为,这是最便携的方式:

dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

#3


3  

This is not as trivial as it looks like. Check out this question and this

这并不像它看起来那么微不足道。看看这个问题吧

#4


0  

alternative method

替代方法

pid=$$
path=$(ps -eo pid,args| awk -vp=$pid '$1~p{print $3}')
case "$path" in
    ./* ) pwd;;
    * ) echo $path;;
esac