Shell 简单入门教程

  • 2021 年 1 月 30 日
  • 笔记

大数据开发岗为什么要学习Shell呢?
1)需要看懂大数据运维岗人员编写的Shell程序。
2)偶尔会编写一些简单Shell程序来管理集群、提高开发效率

艺多不压身

Shell是一个命令行解释器,它接受应用程序/用户命令,然后调用操作系统内核
Shell还是一个功能相当强大的编程语言,易编写,易调试,灵活性强

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

[root@Bigdata ~]$ cat /etc/shells 
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh

Centos默认的解析器是bash

[root@Bigdata bin]$ echo $SHELL
/bin/bash

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

[root@Bigdata shell]$ touch helloworld.sh
[root@Bigdata shell]$ vi helloworld.sh

在helloworld.sh中输入如下内容

#!/bin/bash
echo "helloworld"

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

[root@Bigdata shell]$ sh helloworld.sh 
helloworld

sh+脚本的绝对路径

[root@Bigdata shell]$ sh /opt/shell/helloworld.sh 
helloworld

bash+脚本的相对路径

[root@Bigdata shell]$ bash helloworld.sh 
helloworld

bash+脚本的绝对路径

[root@Bigdata shell]$ bash /opt/shell/helloworld.sh 
helloworld

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

[root@Bigdata shell]$ chmod 777 helloworld.sh

(b)执行脚本
相对路径

[root@Bigdata shell]$ ./helloworld.sh 
helloworld

绝对路径

[root@Bigdata shell]$ /opt/shell/helloworld.sh 
helloworld

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

3.第二个Shell脚本:多命令处理
(1)需求:
在/opt/shell/目录下创建一个huan.txt,在huan.txt文件中增加“huanhuan”。
(2)案例实操:

[root@Bigdata shell]$ touch huan.sh
[root@Bigdata shell]$ vim huan.sh

在huan.sh中输入如下内容

#!/bin/bash

cd /opt/shel
touch huan.txt
echo "huanhuan" >> huan.txt