解决调用shell脚本中相对路径的问题

时间:2022-10-20 15:33:42
依家我有1个软件*目录(大家懂得)
放在/home/gateman/Programs/ 下

1. proxy.py
入面有1个 proxy.py 文件 放在/home/gateman/Programs /*/local/ 入面

2. breakwall.sh
我在 proxy.py 的上一级目录 /home/gateman/Programs /*/
建立1个脚本来启动这个程序. 
 

#!/bin/sh
python ./local/proxy.py


如果进入/home/gateman/Programs /*/ 目录
执行 sh ./breakwall.sh
系无问题的。 正常启动。

但系去到其他目录, 例如上一级的 /home/gateman/Programs/
去执行 sh ./*/breakwall.sh
就会报错


因为在/home/gateman/Programs/ 呢个目录下执行脚步里的
python 
时,./local/proxy.py 被解析为  /home/gateman/Programs /local/proxy.py
而事实上的正确路径应该是 /home/gateman/Programs /*/local/proxy.py
所以就会揾唔到呢个文件。


解决方法1:
将breakwall.sh 的相对路径改为绝对路径:
./local/proxy.py ==>  /home/gateman/Programs/local/proxy.py `
#!/bin/sh
python
那么无论在哪个路径调用这个脚本,都能正常启动程序。

缺陷:

但系这样改的话, 工程迁移会好麻烦, 例如我要将/home/gateman/Programs /*/这个 *软件搬到别路径 或者别的机器下时, 就要修改breakwall.sh文件 修正入面的绝对路径.

解决方法2:
在脚本breakwall.sh 中加入获取 绝对路径的语句。
 

#!/bin/sh
CURDIR="`pwd`"/"`dirname $0`"
echo $CURDIR
python $CURDIR/local/proxy.py

其中pwd 命令 就是 返回当前目录的绝对了路径
$0 就是第0个参数
例如 我在 /home/gateman/Programs/ 执行
sh goegent/breakwall.sh

其中
pwd 就返回 /home/gateman/Programs/
$0   返回   goegent/breakwall.sh
dirname $0返回 goegent/

所以$CURDIR 就= /home/gateman/Programs/goegent/


缺陷:
貌似执行成功,其实可以发现$0这个变量 是由执行命令的路径决定的
这个脚本只能用相对路径来执行

如果我在/home/gateman/Programs/ 用绝对路径来执行
sh /home/gateman/Programs/goegent/breakwall.sh
就会报错了..


原因都好简单, 因为此时$0 就变成/home/gateman/Programs/goegent/breakwall.sh
导致$CURDIR=/home/gateman/Programs/goegent/breakwall.sh


解决方法3:
在breakwall.sh 对$0 进行判断, 对绝对路径和相对路径加入判断。
 

#!/bin/bash
DIRNAME=$0
if [ "${DIRNAME:0:1}" = "/" ];then
    CURDIR=`dirname $DIRNAME`
else
    CURDIR="`pwd`"/"`dirname $DIRNAME`"
fi
echo $CURDIR
python $CURDIR/local/proxy.py


这次无论在什么路径下  用
bash /home/gateman/Programs/goegent/breakwall.sh

bash  相对路径/breakwall.sh

一定要用bash,  sh解析不了这个语法。
${DIRNAME:0:1}
都可以正常启动了。

大家有更好方法的话请指教