IF/THEN BASH 最佳实践

IF/THEN BASH Best Practices

我想知道我是否做对了。我正在尝试学习BASH并且非常想第一次学习"Best Practices",所以我没有采用sloppy/easy方式。

我想知道,我可以像下面那样嵌套 IF/THEN 语句吗?为什么或者为什么不?使用 elif 会更好地为下面的块提供服务吗?

最后,我希望有人能为我阐明“${foo}”和“$(bar)”的用法……大括号或圆括号?我(到目前为止)在定义变量时使用花括号 "foo='bar'" 后来被称为“${foo},当我捕获命令时括号 "foo=$(find . -type f -name bar)" 将被称为“ $foo" ... 或者也许我只是走了很远,做了两次同样的事情,我不知道 ... 我很想听听你们要说什么!:D

# Downloading the script bundle
echo "Lets get the script bundle and get to work!"
wget http://place.to.get/att.tar

# Logic switch, checking if the TAR bundle exists. If it does
# verify the MD5 Checksum (to prevent corruption).
# If verfied, then un-tar the bundle in our working directory
# otherwise, exit with an error code, otherwise 
if [[ -f att.tar ]]
    then
        echo "Okay, we have the bundle, lets verify the checksum"
        sum=$(md5sum /root/att/att.tar | awk '{print }')
            if [[ $sum -eq "xxxxINSERT-CHECKSUM-HERExxxx" ]]
                then
                    tar -xvf att.tar
            else
                clear
                echo "Couldn't verify the MD5 Checksum, something went wrong" | tee /tmp/att.$time.log
                sleep 0.5
                exit 1;
            fi
    else
    clear
    echo "There was a problem getting the TAR bundle, exiting now ..." | tee /tmp/att.$time.log
    sleep 0.5
    exit 1;
fi

总体评价

  • 嵌套没有问题 "if's," 但提前退出会更清楚
  • cut 比 awk 便宜,但 read 仍然便宜
  • 使用“[”而不是“[[”[
  • 的简单字符串相等性测试要便宜一些
  • 将错误消息写入 STDERR
  • 使用 read 和 < <() 而不是 $( | cut -f1 -d' ') 因为它避免了管道和第二个 fork/exec
  • 使用函数

简化版

bail () {
    clear
    echo "${@}" | tee /tmp/att.${time}.log >&2
    exit 1
}

# Downloading the script bundle
echo "Lets get the script bundle and get to work!" >&2
wget http://place.to.get/att.tar || bail "There was a problem getting the TAR bundle, exiting now ..."

sum=''
read sum rest < <(md5sum /root/att/att.tar)

[ $sum == "xxxxINSERT-CHECKSUM-HERExxxx" ] || bail "Couldn't verify the MD5 Checksum, something went wrong"

tar -xvf att.tar || bail "Extract failed"