Shell概述
Shell解析器
(1)Linux提供的Shell解析器有:
[root@hadoop100 learnshell]# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh
(2)bash和sh的关系
[root@hadoop100 learnshell]# ll /bin | grep bash
-rwxr-xr-x. 1 root root 941880 5月 11 2016 bash
lrwxrwxrwx. 1 root root 4 2月 23 08:02 sh -> bash
(3)Centos默认的解析器是bash
[root@hadoop100 learnshell]# echo $SHELL
/bin/bash
Shell脚本入门
- 脚本格式
脚本以#!/bin/bash开头(指定解析器) - 第一个Shell脚本:helloworld
(1)需求:创建一个Shell脚本,输出Hello World!
(2)案例实操:
[root@hadoop100 learnshell]# touch HelloWorld.sh
[root@hadoop100 learnshell]# vim HelloWorld.sh
在HelloWorld.sh中输入如下内容
#!/bin/bash
echo "Hello World!"
(3)脚本的常用执行方式
第一种:采用bash或sh+脚本的相对路径或绝对路径(不用赋予脚本+x权限)
sh+脚本的相对路径
[root@hadoop100 learnshell]# sh HelloWorld.sh
Hello World!
sh+脚本的绝对路径
[root@hadoop100 learnshell]# sh /root/learn/learnshell/HelloWorld.sh
Hello World!
bash+脚本的相对路径
[root@hadoop100 learnshell]# bash HelloWorld.sh
Hello World!
bash+脚本的绝对路径
[root@hadoop100 learnshell]# bash /root/learn/learnshell/HelloWorld.shHello World!
第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)
(a)首先要赋予HelloWorld.sh 脚本的+x权限
[root@hadoop100 learnshell]# ./HelloWorld.sh
-bash: ./HelloWorld.sh: 权限不够
[root@hadoop100 learnshell]# ll
总用量 4
-rw-r--r--. 1 root root 32 2月 25 13:28 HelloWorld.sh
[root@hadoop100 learnshell]# chmod u+x HelloWorld.sh
[root@hadoop100 learnshell]# ll
总用量 4
-rwxr--r--. 1 root root 32 2月 25 13:28 HelloWorld.sh
(b)执行脚本
相对路径
[root@hadoop100 learnshell]# ./HelloWorld.sh
Hello World!
绝对路径
[root@hadoop100 learnshell]# /root/learn/learnshell/HelloWorld.sh
Hello World!
注意:第一种执行方法,本质是bash解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。
- 第二个Shell脚本:多命令处理
(1)需求:
在/root/learn/learnshell/目录下创建一个1.txt,在1.txt文件中增加“I love shell”。
(2)案例实操:
[root@hadoop100 learnshell]# touch 1.sh
[root@hadoop100 learnshell]# vim 1.sh
[root@hadoop100 learnshell]# bash 1.sh
[root@hadoop100 learnshell]# ll
总用量 12
-rw-r--r--. 1 root root 79 2月 25 13:56 1.sh
-rw-r--r--. 1 root root 13 2月 25 13:56 1.txt
-rwxr--r--. 1 root root 32 2月 25 13:28 HelloWorld.sh
[root@hadoop100 learnshell]# cat 1.txt
l love shell
在1.sh中输入内容:
#!/bin/bash
cd /root/learn/learnshell/
touch 1.txt
echo "l love shell" >>1.txt
引用自尚硅谷课件