shell脚本改变工作目录

shell脚本运行的几种方式:
1:添加脚本的执行权限,然后通过路径加文件名的方式运行

chmod +x test.sh;./test.sh

2:source test.sh 或者 . test.sh

3: sh test.sh

后两种方式不必添加脚本的执行权限。怎么改变shell脚本运行的工作目录呢?请看例子:

wpid-screenshot-5.png

[sunliguo@sun sgunicom]$ pwd
/home/sunliguo/sgunicom
[sunliguo@sun sgunicom]$ cat bin/test.sh
#!/bin/bash
cd /
pwd
[sunliguo@sun sgunicom]$ sh bin/test.sh
/
[sunliguo@sun sgunicom]$ pwd
/home/sunliguo/sgunicom
[sunliguo@sun sgunicom]$ chmod +x bin/test.sh
[sunliguo@sun sgunicom]$ bin/test.sh
/
[sunliguo@sun sgunicom]$ pwd
/home/sunliguo/sgunicom
[sunliguo@sun sgunicom]$ source bin/test.sh
/
[sunliguo@sun /]$ pwd
/
[sunliguo@sun /]$ cd –
/home/sunliguo/sgunicom
[sunliguo@sun sgunicom]$ . bin/test.sh
/
[sunliguo@sun /]$ pwd
/
[sunliguo@sun /]$ cd –
/home/sunliguo/sgunicom
[sunliguo@sun sgunicom]$

sh 加脚本名和脚本加执行权限然后运行是shell通过自己的一个子进程来运行的。脚本结束后工作目录并没有改变。点(.)和source是shell的内建命令,运行脚本是通过自身来执行的。

请选择你看完该文章的感受:

0不错 0超赞 0无聊 0扯淡 0不解 0路过

随机文章:

发表评论