Shell笔记1-Shell概述、Shell解析器、Shell脚本入门
原创
©著作权归作者所有:来自51CTO博客作者qq59ce45caba461的原创作品,请联系作者获取转载授权,否则将追究法律责任
Shell概述
Shell编程和我们常见的高级语言编程其实差不多,还是常见的顺序结构、选择结构、循环结构,在语法上略有不同,Shell的外侧是应用程序,内侧是Linux内核,Shell起着联通Linux内核与外部应用程序的作用。
Shell是一个命令行解释器,可以接收应用程序命令和用户命令,再调用操作系统内核实现功能。
Shell还是一个功能强大的编程语言,易编写,易调试,灵活性强。
在Linux操作系统上,如果我们熟练使用Shell,可以将常用的一套命令,编写成一个Shell脚本,后面再碰到相同操作,直接执行脚本即可,大大简化了操作。
Shell解析器
Linux提供的Shell解析器有:
[root@localhost ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
bash和sh的关系
[root@localhost bin]# pwd
/bin
[root@localhost bin]# ll | grep bash
-rwxr-xr-x. 1 root root 964536 4月 1 2020 bash
lrwxrwxrwx. 1 root root 10 6月 8 01:32 bashbug -> bashbug-64
-rwxr-xr-x. 1 root root 6964 4月 1 2020 bashbug-64
lrwxrwxrwx. 1 root root 4 6月 8 01:32 sh -> bash
CentOS默认的解析器是bash
[root@localhost bin]# echo $SHELL
/bin/bash
Shell脚本入门
通常情况下,脚本以#!/bin/bash开头,其中/bin/bash用于指定解析器。
第一个Shell脚本:输出Hello World
创建一个demo.sh,运行demo.sh输出Hello World。
# 进入/opt目录
[root@localhost opt]# cd /opt
[root@localhost opt]# pwd
/opt
# 在/opt目录下创建一个demo.sh,编辑demo.sh
[root@localhost opt]# touch demo.sh
[root@localhost opt]# vim demo.sh
# sh命令执行demo.sh脚本
[root@localhost opt]# sh demo.sh
# bash命令执行demo.sh脚本
[root@localhost opt]# bash demo.sh
Hello World
#!/bin/bash
echo "Hello World"
如果想使用./demo.sh来执行命令,需要给demo.sh赋予执行权限。
# 给demo.sh赋予执行权限
[root@localhost opt]# chmod 777 demo.sh
# ./方式执行demo.sh
[root@localhost opt]# ./demo.sh
Hello World
使用sh和bash是通过解析器来执行的脚本,脚本本身可以不具有执行权限,使用./的方式执行,需要脚本本身可执行。
第二个Shell脚本:多命令处理
在/opt/目录下,创建一个demo.txt文件,在demo.txt文件中增加一段话。
#!/bin/bash
cd /opt/
touch demo.txt
echo "This is demo.txt" >> demo.txt