1. 为什么要学习Shell编程
- Linux运维工程师在进行服务器集群管理时,需要编写Shell程序来进行服务器管理。
- 对于JavaEE和Python程序员来说,工作的需要,你的老大会要求你编写一些Shell脚本进行程序或者是服务器的维护,比如编写一个定时备份数据库的脚本。
- 对于大数据程序员来说,需要编写Shell程序来管理集群。
2. Shell是什么
Shell是一个命令行解释器,它为用户提供了一个向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用Shell来启动、挂起、停止甚至是编写一些程序。
3. Shell脚本的执行方式
1. 脚本格式要求
- 脚本以#!/bin/bash开头
- 脚本需要有可执行权限
- 编写第一个Shell脚本
需求说明:创建一个Shell脚本,输出hello shell
脚本的常用执行方式
方式1(输入脚本的绝对路径或相对路径)
说明:首先要赋予hello.sh 脚本的+x权限,再执行脚本
方式2(sh+脚本)
说明:不用赋予脚本+x权限,直接执行即可。
[root@localhost100 ~]# mkdir /root/shelltest
[root@localhost100 ~]# cd /root/shelltest/
[root@localhost100 shelltest]# ls
[root@localhost100 shelltest]# vim hello.sh
[root@localhost100 shelltest]# ll
总用量 4
-rw-r--r--. 1 root root 31 5月 12 16:18 hello.sh
//赋予可执行权限
[root@localhost100 shelltest]# chmod u+x hello.sh
[root@localhost100 shelltest]# ll
总用量 4
-rwxr--r--. 1 root root 31 5月 12 16:18 hello.sh
[root@localhost100 shelltest]# ./hello.sh
hello shell
[root@localhost100 shelltest]# /root/shelltest/hello.sh
hello shell
[root@localhost100 shelltest]#
//不赋予可执行权限,去掉可执行权限后,执行脚本在前面加上sh
在前面加上sh
[root@localhost100 shelltest]# chmod u-x hello.sh
[root@localhost100 shelltest]# ll
总用量 4
-rw-r--r--. 1 root root 31 5月 12 16:18 hello.sh
[root@localhost100 shelltest]# sh hello.sh
hello shell
[root@localhost100 shelltest]# sh /root/shelltest/hello.sh
hello shell
[root@localhost100 shelltest]#