shell脚本编写小贴士

本文介绍了shell脚本编写与调试的相关技巧。包括让脚本在遭遇不存在的变量或异常时立即终止,将执行内容封装为函数以提高可读性和复用性,使用readonly和local修饰变量,用特定符号代替反单引号,还提及了shell脚本调试方式及自动输入yes的方法。
  1. 当脚本遭遇不存在的变量或异常时立即终止
#!/bin/bash
set -o nounset
set -o errexit

shell脚本执行时,即使遇到不存在的变量,也会继续执行,通过set -o nounset可以避免该问题,当遇到不存在的变量时,脚本会终止执行。
shell脚本执行过程中出现异常,默认会跳过并继续执行,通过set -o errexit可以避免该问题,当脚本执行出错时,会终止脚本运行。
范例:
默认情况:

#!/bin/bash
echo "test"
echo ${exist}
log = ${exits} + 1
echo "go"
执行结果:
test

./t.sh:行4: log: 未找到命令
go

更改后:

#!/bin/bash
set -o nounset
set -o errexit

echo "test"
echo ${exist}
log = ${exits} + 1
echo "go"
执行结果:
test
./t.sh:行6: exist: 未绑定的变量
  1. 尽量封装函数
    当shell脚本执行内容过多时,除了添加注释,还可以通过将一些执行内容封装为函数,可以提高代码的可读性。并且封装后的函数可以复用,降低工作量。
  2. 使用readonly和local修饰变量
  3. 使用$()代替反单引号
  4. 使用[[]]代替[]
  5. shell脚本调试方式
#!/bin/bash
echo "test"
echo ${exist}
log = ${exits} + 1
echo "go"
执行结果:
-v参数会跟踪脚本里每个命令的执行
$ bash -v test.sh
#!/bin/bash
echo "test"
test
echo ${exist}

log = ${exits} + 1
t.sh:行4: log: 未找到命令
echo "go"
go
$ bash -x test.sh
+ echo test
test
+ echo

+ log = + 1
t.sh:行4: log: 未找到命令
+ echo go
go

此外也可以直接在脚本中添加输出调试信息的设置

#!/bin/bash
set -o verbose
set -o xtrace

echo "test"
echo ${exist}
log = ${exits} + 1
echo "go"

7.当安装或者启动某个服务过程中需要输入yes,可以使用echo yes | shell指令

#启动redis集群
echo yes | redis-cli -a redis@CTSI2019 --cluster create 127.0.0.1:18011 127.0.0.1:18012 127.0.0.1:18013 127.0.0.1:18014 127.0.0.1:18015 127.0.0.1:18016 --cluster-replicas 1

此时就可以自动完成yes输入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会画画的画师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值