Shell 脚本入门

1)脚本格式
脚本以#!/bin/bash 开头(指定解析器)
2)第一个 Shell 脚本:helloworld.sh
(1)需求:创建一个 Shell 脚本,输出 helloworld
(2)案例实操:

[atguigu@hadoop101 shells]$ touch helloworld.sh 
[atguigu@hadoop101 shells]$ vim helloworld.sh 
在 helloworld.sh 中输入如下内容 #!/bin/bash echo "helloworld"

(3)脚本的常用执行方式
第一种:采用 bash 或 sh+脚本的相对路径或绝对路径(不用赋予脚本+x 权限) sh+脚本的相对路径

[atguigu@hadoop101 shells]$ sh ./helloworld.sh Helloworld

sh+脚本的绝对路径

[atguigu@hadoop101 shells]$ sh /home/atguigu/shells/helloworld.sh helloworld
bash+脚本的相对路径
[atguigu@hadoop101 shells]$ bash ./helloworld.sh Helloworld

bash+脚本的绝对路径

[atguigu@hadoop101 shells]$ bash /home/atguigu/shells/helloworld.sh Helloworld

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)
①首先要赋予 helloworld.sh 脚本的+x 权限

[atguigu@hadoop101 shells]$ chmod +x helloworld.sh

②执行脚本 相对路径

[atguigu@hadoop101 shells]$ ./helloworld.sh Helloworld

绝对路径

[atguigu@hadoop101 shells]$ /home/atguigu/shells/helloworld.sh Helloworld

注意:第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行 权限。
第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。
【了解】第三种:在脚本的路径前加上“.”或者 source ①有以下脚本

[atguigu@hadoop101 shells]$ cat test.sh #!/bin/bash A=5 echo $A

②分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:

[atguigu@hadoop101 shells]$ bash test.sh
[atguigu@hadoop101 shells]$ echo $A 
[atguigu@hadoop101 shells]$ sh test.sh
[atguigu@hadoop101 shells]$ echo $A
[atguigu@hadoop101 shells]$ ./test.sh 
[atguigu@hadoop101 shells]$ echo $A 
[atguigu@hadoop101 shells]$ . test.sh 
[atguigu@hadoop101 shells]$ echo $A 5

原因: 前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则 子 shell 关闭,回到父 shell 中。
第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前 shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需 要 source 一下的原因。 开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的 当前变量,父 shell 是不可见的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值