美文网首页
如何执行Shell脚本

如何执行Shell脚本

作者: 南风nanfeng | 来源:发表于2018-12-05 11:25 被阅读10次

通常执行shell脚本有两种方式。以脚本/data/shell/test.sh为例:

#!/bin/bash
echo "Please Enter Your Name: "
read yourName
echo "this is your name : "$yourName

    1. 当前目录的方式执行,进入脚本所在目录,即./test.sh,其中./表示当前目录
    1. 全路径方式执行,即/data/shell/test.sh

这两种方式要求脚本具有可执行权限,如果不没有执行权限则给出提示:

[root@sell131 shell]# ./test.sh
-bash: ./test.sh: Permission denied

// 需要先给脚本赋予可执行权限
[root@sell131 shell]# chmod u+x test.sh

实际上还有另外三种执行脚本的方式。

    1. 使用点号“.”
      点号用于执行某个脚本,甚至脚本没有可执行权限也可以运行。有时候在测试运行某个脚本时可能并不想为此修改脚本权限,这时候就可以使用.来运行脚本,非常方便。
[root@sell131 shell]# . ./test.sh 
Please Enter Your Name: 
test
this is your name : test
    1. 使用 source 命令
      与点号类似,source 命令也可读取并在当前环境中执行脚本,同时还可返回脚本中最后一个命令的返回状态;如果没有返回值则返回 0,代表执行成功;如果未找到指定的脚本则返回 false。
[root@sell131 shell]# source test.sh 
Please Enter Your Name: 
test
this is your name : test
    1. 作为解释器参数运行
      这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如:
[root@sell131 logs]# /bin/bash test.sh 
Please Enter Your Name: 
test
this is your name : test

整理自: http://c.biancheng.net/view/739.html

相关文章

网友评论

      本文标题:如何执行Shell脚本

      本文链接:https://www.haomeiwen.com/subject/qojicqtx.html