linux 中调用shell脚本时指定工作目录为shell脚本所在的目录

 

1、

root@DESKTOP-1N42TVH:/home/test# ls root@DESKTOP-1N42TVH:/home/test# ls /home/test2/* /home/test2/a.txt  /home/test2/test.sh root@DESKTOP-1N42TVH:/home/test# cat /home/test2/test.sh     ## shell脚本所在目录及内容 #!/bin/bash wc -l ./a.txt root@DESKTOP-1N42TVH:/home/test# bash /home/test2/test.sh    ## 默认的当前目录是执行脚本的目录, 而不是shell所在的目录,执行脚本的目录下没有a.txt wc: ./a.txt: No such file or directory

 

2、利用

$(dirname $0)  ## 指定工作目录为shell脚本所在的目录

 

修改shell脚本测试:

root@DESKTOP-1N42TVH:/home/test# ls root@DESKTOP-1N42TVH:/home/test# ls /home/test2/* /home/test2/a.txt  /home/test2/test.sh root@DESKTOP-1N42TVH:/home/test# cat /home/test2/test.sh #!/bin/bash dir=$(dirname $0)                   ## 指定工作目录为shlle脚本所在的目录 wc -l $dir/a.txt root@DESKTOP-1N42TVH:/home/test# bash /home/test2/test.sh      ## a.txt在shell所在的目录,故可以输出行数 5 /home/test2/a.txt