IF / THEN BASH最佳实践

时间:2015-04-17 00:01:18

标签: bash if-statement logic

我想知道我是否做得对。我正在努力学习BASH并且真的想学习"最佳实践"第一次,所以我不采取草率/简单的方式。

我想知道的是,我能否像以下一样完成IF / THEN声明?为什么或者为什么不?使用elif代替下面的块会更好吗?

最后,我希望有人可以为我使用" $ {foo}"和" $(bar)" ...花括号或括号?我定义一个变量" foo =' bar'"'''''''''''''''当我捕获命令" foo = $(找到.- type f -name bar)"后来被称为" $ {foo}和括号。将被称为" $ 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 $1}')
            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

1 个答案:

答案 0 :(得分:2)

总体评论

  • 嵌套" if' s"没有错但提前退出会更清楚
  • cut比awk便宜,但阅读更便宜
  • 简单的字符串相等测试与#34; ["而不是" [["
  • 将错误消息写入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"