Shell脚本 (一) 概述、解析器、脚本入门

一、 Shell 脚本概述

1、 Shell 的 含义:

Shell 是一个用C语言编写的程序,它是用户使用Linux 的桥梁。Shell既是一种命令语言,又是一种程序设计语言。

Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务。

Ken Thompson 的 sh 是第一种 Unix Shell,Windows Explorer 是一个典型的图形界面 Shell。

Shell 在线工具

2、Shell 脚本

Shell 脚本(shell script),是一种为 shell 编写的脚本程序。

Shell是一个命令解释器,是一个程序/bin/bash,解释linux的命令

注意:

  •      shell交互式命令使用
  •      打开终端,一行行敲命令

Shell script  是利用shell的功能所写的一个程序,这个程序是使用纯文本文件,将一些shell的语法与指令写在里面,然后用正规表示法,管道命令以及数据流重导向等功能,以达到我们所想要的处理目的。

二、Shell 解析器

1、Linux 提供的Shell解析器有:

查看Shell解析器命令:       sudo cat /etc/shells

如下图:

2、bash 和 sh  的关系:

可见两者关系为软连接,sh 最终指向的是 bash

命令: ll | grep bash

3、Centos 默认的解析器是bash

命令: echo $SHELL

三、Shell脚本入门

1、 脚本格式

脚本 以 #!/bin/bash 开头(指定解析器)

2、 第一个Shell脚本: hellWorld

(1) 需求: 创建一个Shell脚本,输出helloworld

(2)案例实操

[root@rich wenmin]# mkdir datas
[root@rich wenmin]# cd datas
[root@rich datas]# pwd
/home/wenmin/datas
[root@rich datas]# touch helloworld.sh
[root@rich datas]# vim helloworld.sh 

在 helloworld.sh 中输入如下内容:

#!/bin/bash

echo "helloworld wenmin"

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

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

sh+脚本的相对路径

[root@rich datas]# ll
总用量 4
-rw-r--r-- 1 root root 38 4月 30 20:26 helloworld.sh [root@rich datas]# sh helloworld.sh helloworld wenmin [root@rich datas]# 

sh+ 脚本的绝对路径

[root@rich datas]# pwd
/home/wenmin/datas
[root@rich datas]# sh /home/wenmin/datas/helloworld.sh 
helloworld wenmin
[root@rich datas]#

bash + 脚本的相对路径

[root@rich datas]# bash helloworld.sh 
helloworld wenmin
[root@rich datas]# 

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

(a)首先要赋予 helloworld.sh 脚本的 +x 权限

[root@rich datas]# ./helloworld.sh
-bash: ./helloworld.sh: 权限不够
[root@rich datas]# chmod 777 helloworld.sh
[root@rich datas]# ll

(b)执行脚本

相对路径

[root@rich datas]# ./helloworld.sh 
helloworld wenmin

绝对路径

[root@rich datas]# /home/wenmin/datas/helloworld.sh 
helloworld wenmin

注意:

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

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

3、第二个Shell 脚本: 多命令处理

(1)需求:

   在 /home/wenmin/ 目录下创建一个wenxing.txt,在wenxing.txt文件中增加 "I love cls".

(2)案例实操:

[root@rich datas]# touch batch.sh
[root@rich datas]# vim batch.sh 

在 batch.sh 中输入如下内容:

#!/bin/bash

cd /home/wenmin/
touch wenxing.txt
echo "I love cls" >>wenxing.txt
//执行Shell脚本

[root@rich datas]# ll
总用量 8
-rw-r--r-- 1 root root 80 4月 30 20:52 batch.sh -rwxrwxrwx 1 root root 38 4月 30 20:26 helloworld.sh [root@rich datas]# bash batch.sh 

查看目录文件及 wenxing.txt 内容

[root@rich wenmin]# ll
总用量 8
drwxr-xr-x 2 root root 4096 4月  30 20:56 datas
-rw-r--r-- 1 root root   11 4月  30 20:52 wenxing.txt
[root@rich wenmin]# cat wenxing.txt 
I love cls

猜你喜欢

转载自www.cnblogs.com/wushaopei/p/11979248.html