快速入门Shell脚本(1)——Shell脚本的介绍

在这里插入图片描述

1.什么是shell

同时它又是一种程序设计语言。作为命令语言,它交互式解释和执行用户输入的命令或者自动地解释和执行预先设定好的一连串的命令;作为程序设计语言,它定义了各种变量和参数,并提供了许多在高级语言中才具有的控制结构,包括循环和分支。

2.Shell概述

大数据程序员为什么要学习Shell呢?

  1. 需要看懂运维人员编写的Shell程序。
  2. 偶尔会编写一些简单Shell程序来管理集群、提高开发效率。
    在这里插入图片描述

3.shell解析器

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

[root@node01 bin]# cat /etc/shells
/bin/sh
/bin/bash

/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh

  1. bash和sh的关系

[root@node01 bin]# ll | grep bash
-rwxr-xr-x. 1 root root 942200 3月 23 2017 bash
lrwxrwxrwx. 1 root root 4 1月 4 2020 sh -> bash

  1. Centos默认的解析器是bash

[root@node01 bin]# echo $SHELL
/bin/bash

4.Shell脚本入门

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

 [root@node01 bin]$ touch helloworld.sh
 [root@node01 bin]$ vi helloworld.sh
 
#在helloworld.sh中输入如下内容
#!/bin/bash
echo "helloworld"

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

[root@node01 bin]$ sh helloworld.sh 
Helloworld
#sh+脚本的绝对路径
[root@node01 bin]$ sh /home/atguigu/datas/helloworld.sh 
helloworld
#bash+脚本的相对路径
[root@node01 bin]$ bash helloworld.sh 
Helloworld
#bash+脚本的绝对路径
[root@node01 bin]$ bash /home/atguigu/datas/helloworld.sh 
Helloworld

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

[root@node01 bin]$ chmod 777 helloworld.sh

(b)执行脚本

[root@node01 bin]$ ./helloworld.sh 
Helloworld

绝对路径

扫描二维码关注公众号,回复: 11441663 查看本文章
[root@node01 bin]$ /home/atguigu/datas/helloworld.sh 
Helloworld

注意第一种执行方法,本质是bash解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。
3.第二个Shell脚本:多命令处理
(1)需求:
在/home/atguigu/目录下创建一个banzhang.txt,在banzhang.txt文件中增加“I love cls”。
(2)案例实操:

[root@node01 bin]$ touch batch.sh
[root@node01 bin]$ vi batch.sh

#在batch.sh中输入如下内容
#!/bin/bash
cd /home/atguigu
touch cls.txt
echo "I love cls" >>cls.txt

猜你喜欢

转载自blog.csdn.net/qq_43791724/article/details/107528590