您的位置:首页 > 运维架构 > Shell

[备忘] - 关于shell中使用pwd来取目录的用法

2013-11-21 11:12 253 查看
这个问题在我一次写脚本的时候发现的,手动执行脚本OK,但是放在cron中就不行(通过把计划任务的log重定向出来发现问题的)。主要有下面2个问题,记下来备忘:

1. 关于命令未发现

crontab运行的时候,提示找不到mysql的命令,后来在脚本中加入

#!/bin/bash
set -x
echo $PATH


输出只有 /bin:/sbin

解决的方法:在脚本中,导入环境变量

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin


2. 关于想使用`pwd`取脚本的所在目录

在脚本中使用

_work=`pwd`

_work 得到的是你当前执行脚本的位置;比如说我的脚本放置在/root/test.sh 和 /root/py/test.sh

脚本的内容如下

#!/bin/bash

_work=`pwd`

echo $_work

实际上取的是你当前所在的位置,而不是脚本存放位置的目录

[root@localhost ~]# ll /root/test.sh
-rwxr-xr-x. 1 root root 50 Nov 21 10:33 /root/test.sh
[root@localhost ~]# ll /root/py/test.sh
-rwxr-xr-x. 1 root root 50 Nov 21 10:17 /root/py/test.sh
[root@localhost ~]# cd /tmp/
[root@localhost tmp]# /root/test.sh
/tmp
[root@localhost tmp]# /root/py/test.sh
/tmp

PS: 那在不同的位置执行这个脚本,得到的并不是我们想要的_work=/root/scripts

# 取代的方法

#!/bin/bash
_work=`dirname $0`
echo $_work
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐