bash脚本执行方式

1、脚本中命令在子shell(sub shell)中执行

    bash 可执行文件名    
    可执行文件名

2、脚本中命令在当前shell中执行

   source  可执行文件名
   .  可执行文件名

3、实例

       [root@centos6 ~]# pwd
        /root
        ##shell脚本切换目录,然后查看目录内容
        [root@centos6 ~]# cat test.sh
        #!/bin/bash
        
        cd /home/dog
        ls
        
        [root@centos6 ~]# 
        [root@centos6 ~]# chmod u+x test.sh
        ##子shell方式执行,当前shell环境不受影响(没有切换到shell脚本中的新目录)
        [root@centos6 ~]# bash test.sh
        a.txt  b.py  ddd  ddd.txt  lit	source	target	target2  txt.tar
        [root@centos6 ~]# pwd
        /root
        [root@centos6 ~]# ./test.sh
        a.txt  b.py  ddd  ddd.txt  lit	source	target	target2  txt.tar
        [root@centos6 ~]# pwd
        /root
        
        ##当前shell方式执行,当前shell环境受影响(切换到shell脚本中的新目录)
        [root@centos6 ~]# . test.sh
        a.txt  b.py  ddd  ddd.txt  lit  source  target  target2  txt.tar
        [root@centos6 dog]# pwd
        /home/dog
        [root@centos6 dog]# cd -
        /root
        [root@centos6 ~]# pwd
        /root
        [root@centos6 ~]# 
        [root@centos6 ~]# source ./test.sh
        a.txt  b.py  ddd  ddd.txt  lit  source  target  target2  txt.tar
        [root@centos6 dog]# pwd
        /home/dog

4、命令在子shell中执行

用小括号括起来的命令在子shell中执行,不影响当前shell环境

(命令)
[root@centos6 ~]# pwd
/root
[root@centos6 ~]# 
[root@centos6 ~]# 
[root@centos6 ~]# (cd /home/; ls)
dog  duanyi  hack  jmz  qiaofeng  sx  test1.txt  test2.txt  testuser1  testuser2  tony
[root@centos6 ~]# 
[root@centos6 ~]# pwd
/root

你可能感兴趣的:(linux)