2、Shell 脚本入门

本文介绍了Shell脚本的基础知识,包括脚本格式和执行方式。通过创建并执行helloworld.sh脚本,展示了三种不同的执行方法:使用bash或sh执行脚本的路径,以及赋予脚本执行权限后通过相对或绝对路径执行。还讲解了在脚本前加'.'或'source'执行的区别,特别是在设置环境变量时的影响。
摘要由CSDN通过智能技术生成


尚硅谷2022版Linux扩展篇Shell教程-讲师:武晟然

壁立千仞 无欲则刚

2、Shell 脚本入门

2.1 脚本格式

后缀是.sh不写也是可以运行,但是约定俗成
脚本文本以#!/bin/bash开头(指定解析器)
文本#为注释

2.2 第一个 Shell 脚本:helloworld.sh

(1)需求:创建一个 Shell 脚本,输出 helloworld
(2)案例实操:

[root@centos7-101 ~]# mkdir scripts
[root@centos7-101 scripts]# touch helloworld.sh
[root@centos7-101 scripts]# vim helloworld.sh

在 helloworld.sh 中输入如下内容

#!/bin/bash
echo "helloworld" 

(3)脚本的常用执行方式

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

sh+脚本的相对路径(当前路径./)

[root@centos7-101 scripts]# sh ./helloworld.sh 
hello word

sh+脚本的绝对路径

[root@centos7-101 scripts]# sh /root/script/helloworld.sh 
hello word

bash+脚本的相对路径

[root@centos7-101 scripts]# bash ./helloworld.sh 
hello word
[root@centos7-101 scripts]# bash helloworld.sh 
hello word

bash+脚本的绝对路径

[root@centos7-101 scripts]# bash /root/script/helloworld.sh 
hello word

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

①首先要赋予 helloworld.sh 脚本的+x 权限

[root@centos7-101 scripts]# chmod u+x helloworld.sh

②执行脚本
相对路径

[root@centos7-101 scripts]# ./helloworld.sh 
hello word

绝对路径

[root@centos7-101 scripts]# /root/script/helloworld.sh 
hello word

注意:

第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行权限。

第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。

想要写helloworld.sh直接执行,需要在环境变量中添加helloworld.sh所在的目录。

[root@centos7-101 scripts]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

【了解】第三种:在脚本的路径前加上“.”或者 source

①有以下脚本

[root@centos7-101 scripts]# touch test.sh
[root@centos7-101 scripts]# vim test.sh
[root@centos7-101 scripts]# chmod u+x ./test.sh 
[root@centos7-101 scripts]# cat test.sh 
#!/bin/bash
# 对环境变量A赋值
A=5
# 取出A值
echo $A

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

[root@centos7-101 scripts]# bash test.sh 
5
[root@centos7-101 scripts]# echo $A

sh

[root@centos7-101 scripts]# sh test.sh 
5
[root@centos7-101 scripts]# echo $A

./

[root@centos7-101 scripts]# ./test.sh 
5
[root@centos7-101 scripts]# echo $A

.

[root@centos7-101 scripts]# . test.sh 
5
[root@centos7-101 scripts]# echo $A
5

与前两种区别:

source是bash的内置命令,本身是csh中的,另一种实现是bash的”.“,所以”.“与source效果相同。

bash、sh、./helloworld.sh本质上都是打开了一个子Shell进程,当前的Shell环境不受影响,

“.”或者 source 是不启动子Shell进程的,直接在当前的Shell进程中执行,好处是没有父子环境嵌套,可以设置一些环境变量,如果有父子嵌套,在子Shell设置环境变量,父Shell中是获取不到的。

原因:
前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。

第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需要 source 一下的原因。

开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的当前变量,父 shell 是不可见的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值