BASH 的非官方严格模式

Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)

使用非官方的严格模式 (除非你喜欢debug)

对原作者表示尊重:(http://redsymbol.net/articles/unofficial-bash-strict-mode/)

核心是在脚本中采用这样的头部:

#! /bin/bash
set -euo pipefail
IFS=$'\n\t'

目的是让脚本变得更加健壮,让一下模糊的,不确定的,隐形的错误,显示出来,利于更好的控制

set -e

这个参数设定,但命令返回非0时退出脚本。意思是在脚本中对出现的错误进行零容忍。
但是有时候,可能在脚本中执行一些期望报错的命令,该怎么办呢?可以这样:

# "grep -c" reports the number of matching lines. If the number is 0,
# then grep's exit status is 1, but we don't care - we just want to
# know the number of matches, even if that number is zero.

# Under strict mode, the next line aborts with an error:
count=$(grep -c some-string some-file)

# But this one behaves more nicely:
count=$(grep -c some-string some-file || true)

echo "count: $count"

可以让这行命令不报错。
当然也可以临时性的去掉-e模式,
这样:

# We had started out this script with set -e . And then...

set +e
count=$(grep -c some-string some-file)
retval=$?
set -e

# grep's return code is 0 when one or more lines match;
# 1 if no lines match; and 2 on an error. This pattern
# lets us distinguish between them.

echo "return value: 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值