Shell 入门

一、简介

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

 二、Shell 解析器

(1)Linux 提供的 Shell 解析器有:

[root@centos7 ~]# cat /etc/shells 
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
/bin/tcsh
/bin/csh

(2)bash 和 sh 的关系

[root@centos7 ~]# cd /bin/
[root@centos7 bin]# ll | grep bash
-rwxr-xr-x.   1 root root      964536 4月   1 2020 bash
lrwxrwxrwx.   1 root root          10 4月  26 16:45 bashbug -> bashbug-64
-rwxr-xr-x.   1 root root        6964 4月   1 2020 bashbug-64
lrwxrwxrwx.   1 root root           4 4月  26 16:45 sh -> bash
[root@centos7 bin]# 

(3)Centos 默认的解析器是bash

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

三、Shell 脚本入门

1、脚本格式

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

2、第一个Shell脚本

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

(2)案例实操:

[root@centos7 shell_test]# touch helloworld.sh
[root@centos7 shell_test]# vim helloworld.sh

在helloworld.sh中输入如下内容
#!/bin/bash
echo "helloworld"

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

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

#sh+脚本的相对路径
[root@centos7 shell_test]# sh helloworld.sh

#sh+脚本的绝对路径
[root@centos7 shell_test]# sh /home/atguigu/datas/helloworld.sh

#bash+脚本的相对路径
[root@centos7 shell_test]# bash helloworld.sh

#bash+脚本的绝对路径
[root@centos7 shell_test]# bash /home/atguigu/datas/helloworld.sh

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

#1、首先要赋予helloworld.sh 脚本的+x权限
[root@centos7 shell_test]# chmod 777 helloworld.sh

#2、执行脚本
#相对路径
[root@centos7 shell_test]# ./helloworld.sh

#绝对路径
[root@centos7 shell_test]# /home/atguigu/datas/helloworld.sh

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

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

(1)需求:

在 /opt/shell_test/ 目录下创建一个 banzhang.txt,在 banzhang.txt 文件中增加“I love cls”。

(2)案例实操:

[root@centos7 shell_test]# touch batch.sh
[root@centos7 shell_test]# vim batch.sh

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

 

posted @ 2021-06-23 11:33  认真对待世界的小白  阅读(76)  评论(0编辑  收藏  举报