如何执行Shell脚本

通常执行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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。