zoukankan      html  css  js  c++  java
  • shell脚本4种执行方式

    Linux中shell脚本的执行通常有4种方式,分别为工作目录执行,绝对路径执行,sh执行,shell环境执行。

    首先,看下我们的脚本内容

    [tan@tan scripts]$ ll
    total 4
    -rw-rw-r--. 1 tan tan 68 May  8 23:18 test.sh
    [tan@tan scripts]$ cat test.sh 
    #!/usr/bin/bash
    
    /usr/bin/python <<-EOF
    print "Hello Shell"
            EOF

    1、工作目录执行

    工作目录执行,指的是执行脚本时,先进入到脚本所在的目录(此时,称为工作目录),然后使用 ./脚本方式执行

    [tan@tan scripts]$ ./test.sh
    -bash: ./test.sh: Permission denied
    [tan@tan scripts]$ chmod 764 test.sh
    [tan@tan scripts]$ ./test.sh
    Hello Shell

    如图,报了权限错误,上一篇博文有提到,这里需要赋权,使用chmod 764 test.sh 赋权后就可以正常执行了

    ./的意思是说在当前的工作目录下执行hello.sh。如果不加上./,bash可能会响应找到不到hello.sh的错误信息。因为目前的工作目录 (/data/shell)可能不在执行程序默认的搜索路径之列,也就是说,不在环境变量PASH的内容之中。查看PATH的内容可用 echo $PASH 命令。现在的/data/shell就不在环境变量PASH中的,所以必须加上./才可执行。

    2、绝对路径执行

    绝对路径中执行,指的是直接从根目录/到脚本目录的绝对路径

    [tan@tan scripts]$ pwd
    /home/tan/scripts
    [tan@tan scripts]$ `pwd`/test.sh 
    Hello Shell
    [tan@tan scripts]$ /home/tan/scripts/test.sh 
    Hello Shell

    这里 `pwd` 指的是该命令执行结果,等同于 /home/tan/scripts

    3、sh执行

    sh执行,指的是用脚本对应的sh或bash来接着脚本执行

    [tan@tan scripts]$ sh test.sh 
    Hello Shell
    [tan@tan scripts]$ bash test.sh 
    Hello Shell

    注意,若是以方法三的方式来执行,那么,可以不必事先设定shell的执行权限,甚至都不用写shell文件中的第一行(指定bash路径)。因为方法三 是将hello.sh作为参数传给sh(bash)命令来执行的。这时不是hello.sh自己来执行,而是被人家调用执行,所以不要执行权限。那么不用 指定bash路径自然也好理解了啊,呵呵……。

    4、shell环境执行

    shell环境执行,指的是在当前的shell环境中执行,可以使用 . 接脚本 或 source 接脚本

    [tan@tan scripts]$ . test.sh 
    Hello Shell
    [tan@tan scripts]$ source test.sh 
    Hello Shell
  • 相关阅读:
    hdu 1269 迷宫城堡 (并查集)
    hdu 1272 小希的迷宫 (深搜)
    hdu 1026 Ignatius and the Princess I (深搜)
    hdu 1099 Lottery
    hdu 1068 Girls and Boys (二分匹配)
    几个基础数位DP(hdu 2089,hdu 3555,uestc 1307 windy 数)
    hdu 1072 Nightmare (广搜)
    hdu 1398 Square Coins (母函数)
    hdu 1253 胜利大逃亡 (深搜)
    hdu 1115 Lifting the Stone (求重心)
  • 原文地址:https://www.cnblogs.com/tan-y-q/p/10835956.html
Copyright © 2011-2022 走看看