shell获取当前工作目录绝对路径

一般我们写Shell脚本的时候,都倾向使用绝对路径,这样无论脚本在什么目录执行,都应该起到相同的效果,但是有些时候,我们设计一个软件包中的工具脚本或者远程调用某个脚本时,可能使用相对路径更加灵活一点,因为你不知道用户会在哪个目录执行你的程序,于是问题就来了,如何获取当前正在执行脚本的绝对路径?

常见的一种误区,是使用 pwd 命令,该命令的作用是“print name of current/working directory”,这才是此命令的真实含义,当前的工作目录,这里没有任何意思说明,这个目录就是脚本存放的目录。所以,这是不对的。你可以试试bash shell/a.sh,a.sh 内容是 pwd,你会发现,显示的是执行命令的路径 /home/ljl,并不是 a.sh 所在路径:/home/ljl/shell/a.sh

另一个误人子弟的答案,是 $0,这个也是不对的,这个$0是Bash环境下的特殊变量,其真实含义是:

Expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, 
$0
 is set to the name of that file. If bash is started with the -c option, then 
$0
is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero.

这个$0有可能是好几种值,跟调用的方式有关系:

使用一个文件调用bash,那$0的值,是那个文件的名字(没说是绝对路径噢)

使用-c选项启动bash的话,真正执行的命令会从一个字符串中读取,字符串后面如果还有别的参数的话,使用从$0开始的特殊变量引用(跟路径无关了)

除此以外,$0会被设置成调用bash的那个文件的名字(没说是绝对路径)

简单介绍一下获取方法如下:

#!/bin/bashthis_dir=`pwd`echo "$this_dir ,this is pwd"echo "$0 ,this is \$0"dirname $0|grep "^/" >/dev/nullif [ $? -eq 0 ];then
    this_dir=`dirname $0`else
    dirname $0|grep "^\." >/dev/null
     retval=$?if [ $retval -eq 0 ];then
    this_dir=`dirname $0|sed "s#^.#$this_dir#"`else
    this_dir=`dirname $0|sed "s#^#$this_dir/#"`fi
 fi
 echo $this_dir

总结一下其实就是一条命令:

base_dir=$(cd "$(dirname "$0")";pwd)
dirname 
$0
,取得当前执行的脚本文件的父目录
cd 
dirname $0
,进入这个目录(切换当前工作目录)
pwd,显示当前工作目录(cd执行后的)


我今天遇到一个问题就是:

需要压缩备份一个目录下的所有的文件,其实代码就2行:

我还是贴全部的吧,最后2行是我的:

#!/bin/bash
this_dir=`pwd`
echo "$this_dir ,this is pwd"
echo "$0 ,this is \$0"
dirname $0|grep "^/" >/dev/null
if [ $? -eq 0 ];then
    this_dir=`dirname $0`
else
    dirname $0|grep "^\." >/dev/null
     retval=$?
if [ $retval -eq 0 ];then
    this_dir=`dirname $0|sed "s#^.#$this_dir#"`
else
    this_dir=`dirname $0|sed "s#^#$this_dir/#"`
fi
 fi
 echo $this_dir
date=`date +%Y%m%d%H%M` 
tar -czvf /root/test/FTP_DATA_$date.tar.gz /FTP_DATA

如上,如果不加上边的,当你执行shell脚本的时候,会报找不到文件,加上之后就好了,大家一起讨论学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值