【Shell】传参
背景:一个用于备份MySQL的某个数据库的shell脚本,每天备份两次,保留3天的备份,运行的很稳定。
由于业务的需求,还需要备份另外一个数据库,由于数据的类型不同,这个库备份的频率可以降低至每周备份一次,保留2个副本即可。
同样的备份,只是数据库不同,保留策略不同,如果简单一点儿的话,直接copy一份儿shell脚本稍微改下即可,显然这不是工作的正确姿势。
实现功能最简单的方法就是,在调用shell时通过传参的方式改变shell的动作。这样改动小且简单明了。
具体的脚本就不贴了,只演示一下shell传参
1:创建一个shell脚本文件,内容如下
1 2 3 4 |
[oracle@msp test]$ cat t.sh #!/bin/bash str=$1 echo $str |
代码非常少,主要是第二行的 $1,指的是第一个参数
2:测试
1 2 3 |
[oracle@msp test]$ sh t.sh "hello world" hello world [oracle@msp test]$ |
由于并没有给t.sh执行权限,所以利用sh直接执行。赋权后执行,效果是一样的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[oracle@msp test]$ ll total 4 -rw-r--r--. 1 oracle oinstall 29 Sep 19 17:00 t.sh [oracle@msp test]$ [oracle@msp test]$ [oracle@msp test]$ chmod u+x t.sh [oracle@msp test]$ [oracle@msp test]$ ll total 4 -rwxr--r--. 1 oracle oinstall 29 Sep 19 17:00 t.sh [oracle@msp test]$ [oracle@msp test]$ ./t.sh "hello world" hello world [oracle@msp test]$ |
3:如果两个参数,效果如下:
1 2 3 4 5 6 7 8 9 |
[oracle@msp test]$ cat t.sh #!/bin/bash str1=$1 str2=$2 echo $str1 $str2 [oracle@msp test]$ [oracle@msp test]$ ./t.sh "hello" "world" hello world [oracle@msp test]$ |
4:小结:
$0:表示程序本身,$1,$2,$3….表示第几个参数
shell中参数还有好多种类型,本人使用shell有限,用到哪儿学到哪儿。