Skip to content

Shell 脚本入门

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

1. Linux提供的Shell解析器

sh
[root@hadoop100 ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

2. bash和sh的关系

Alt text

3. 查看Centos默认的解析器

sh
[root@hadoop100 ~]# echo $SHELL
/bin/bash

4. Shell脚本格式

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

5. 脚本的常用执行方式

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

sh
## sh+脚本的相对路径
[root@hadoop100 shell_learn]# sh ./helloworld.sh 
helloworld
## sh+脚本的绝对路径
[root@hadoop100 shell_learn]# sh /root/shell_learn/helloworld.sh
helloworld
## bash+脚本的相对路径
[root@hadoop100 shell_learn]# bash ./helloworld.sh
helloworld
## bash+脚本的绝对路径
[root@hadoop100 shell_learn]# bash /root/shell_learn/helloworld.sh
helloworld

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

sh
## 赋予 helloworld.sh 脚本的+x 权限
[root@hadoop100 shell_learn]# chmod +x helloworld.sh
## 执行脚本+ 相对路径
[root@hadoop100 shell_learn]# ./helloworld.sh
## 执行脚本+ 绝对路径
[root@hadoop100 shell_learn]# /root/shell_learn/helloworld.sh
## 如果不加./ 会被Linux是一个命令
[root@hadoop100 shell_learn]# helloworld.sh
-bash: helloworld.sh: 未找到命令

提示

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

5.3 使用.或者source执行脚本的相对路径或绝对路径

sh
## .+脚本的相对路径
[root@hadoop100 shell_learn]# . ./helloworld.sh 
helloworld
## .+脚本的绝对路径
[root@hadoop100 shell_learn]# . /root/shell_learn/helloworld.sh
helloworld
## source+脚本的相对路径


[root@hadoop100 shell_learn]# source ./helloworld.sh 
helloworld
## source+脚本的绝对路径
[root@hadoop100 shell_learn]# source /root/shell_learn/helloworld.sh
helloworld

本身是一个命令,source和. 来自csh的写法, 前面sh\bash还有直接执行脚本方式都是调用bash,bash服务启动一个子进程来执行脚本,相当于存在一个父子shell进程的嵌套环境,父子shell的作用范围不同, 而source和. 直接是父shell执行。也就意味着我们编写的shell脚本如果用第一和第二种方式执行,都会用到子shell进程。

sh
[root@hadoop100 shell_learn]# bash
[root@hadoop100 shell_learn]# exit
exit
[root@hadoop100 shell_learn]#

可见没有退出登录root, 原因在于bash执行后会进入一个子shell中,exit只是退出子shell。