Linux学习Day6:编写Shell脚本
Shell脚本命令的工作方式有两种:
交互式(Interactive):用户每输入一条命令就立即执行。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。批处理(Batch):由用户事先编写好一个完整的Shell脚本,Shell会一次性执行脚本中诸多的命令。
一、编写简单的脚本
一个Shell脚本主要由三部分组成:脚本声明、脚本注释、脚本命令。
脚本声明:告诉系统使用哪种Shell解释器来执行该脚本,比如:#!/bin/bash
脚本注释:以#开头,主要是介绍脚本的功能和某些命令
脚本命令:需要被执行的Linux命令。
Shell脚本的名称可以任意,但为了方便用户辨认,建议加上.sh后缀以表示这是一个脚本文件。下面通过Vim编辑器简单编写一个Shell脚本:
[root@linuxprobe ~]# vim example.sh #!/bin/bash //脚本声明 # for example by xuliang //脚本注释 pwd //脚本命令 ls -al
可以通过bash命令直接运行脚本文件,也可以通过输入完整路径的方式来执行,但是需要先对脚本文件添加可执行权限。
[root@linuxprobe ~]# bash example.sh //通过bash命令执行脚本文件 /root total 21260 dr-xr-x---. 17 root root 4096 Feb 23 16:57 . drwxr-xr-x. 17 root root 4096 Feb 23 10:34 .. drwxr-xr-x. 3 root root 14 Feb 18 15:26 a -rw-------. 1 root root 1032 Feb 18 2019 anaconda-ks.cfg -rw-------. 1 root root 6039 Feb 23 10:57 .bash_history ---------------------省略部分输出内容------------------------------ [root@linuxprobe ~]# ./example.sh //通过完整路径执行脚本文件,需要可执行权限
-bash: ./example.sh: Permission denied [root@linuxprobe ~]# chmod u+x example.sh //添加可执行权限 [root@linuxprobe ~]# [root@linuxprobe ~]# ./example.sh //脚本执行成功 /root total 21260 dr-xr-x---. 17 root root 4096 Feb 23 16:57 . drwxr-xr-x. 17 root root 4096 Feb 23 10:34 .. drwxr-xr-x. 3 root root 14 Feb 18 15:26 a -rw-------. 1 root root 1032 Feb 18 2019 anaconda-ks.cfg -rw-------. 1 root root 6039 Feb 23 10:57 .bash_history -------------------省略部分输出内容-----------------------------
二、接收用户的参数
上面的脚本只能执行一些预先定义好的命令,未免太过于死板了。为了增加Shell脚本的灵活性,必须让脚本可以接收用户输入的参数。Linux系统中的Shell脚本语言已经内设了用于接受参数的变量,变量之间使用空格间隔,相关变量如下所示:
- $0:表示当前Shell脚本的名称;
- $#:表示总共有几个参数;
- $*:表示所有位置的参数值
- $1、$2、$3、$4.....:表示第N个位置的参数值。
“百闻不如一见,看书不如实践”,接下来通过编写一个脚本,引用上面的变量参数来看一下实际效果:
[root@linuxprobe ~]# vim example.sh #!/bin/bash # for example by xuliang echo "当前脚本名称$0" echo "总共有$#个参数,分别是$*" echo "第一个参数为$1,第3为$3"
[root@linuxprobe ~]# bash example.sh 1 2 3 4 5 6 //传入6个参数 当前脚本名称example.sh 总共有6个参数,分别是1 2 3 4 5 6 第一个参数为1,第3为3

更多精彩