通常咱们写Shell脚本的时候,都倾向使用绝对路径,这样不管脚本在什么目录执行,都应该起到相同的效果,可是有些时候,咱们设计一个软件包中的工具脚本或者远程调用某个脚本时,可能使用相对路径更加灵活一点,由于你不知道用户会在哪一个目录执行你的程序,因而问题就来了,如何获取当前正在执行脚本的绝对路径?python
常见的一种误区,是使用 pwd 命令,该命令的做用是“print name of current/working directory”,
这才是此命令的真实含义,当前的工做目录,这里没有任何意思说明,这个目录就是脚本存放的目录。因此,这是不对的。你能够试试bash shell/a.sh
,a.sh 内容是 pwd,你会发现,显示的是执行命令的路径 /home/ljl
,并非 a.sh 所在路径:/home/ljl/shell/a.sh
shell
另外一个误人子弟的答案,是 $0
,这个也是不对的,这个$0
是Bash环境下的特殊变量,其真实含义是: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
开始的特殊变量引用(跟路径无关了)this
除此之外,$0
会被设置成调用bash的那个文件的名字(没说是绝对路径)spa
简单介绍一下获取方法以下:设计
#!/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
总结一下其实就是一条命令:code
base_dir=$(cd "$(dirname "$0")";pwd)
dirname $0 ,取得当前执行的脚本文件的父目录 cd dirname $0 ,进入这个目录(切换当前工做目录) pwd,显示当前工做目录(cd执行后的)
我今天遇到一个问题就是:orm
须要压缩备份一个目录下的全部的文件,其实代码就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脚本的时候,会报找不到文件,加上以后就行了,你们一块儿讨论学习