【问题标题】:IF/THEN BASH Best PracticesIF/THEN BASH 最佳实践
【发布时间】:2015-04-17 00:01:18
【问题描述】:

我想知道我是否做得对。我正在努力学习BASH,并且很想第一次学习“最佳实践”,所以我不采用马虎/简单的方法。

我想知道的是,我可以像下面那样嵌套一个 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 $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

【问题讨论】:

  • 花括号用于变量扩展(在许多情况下是可选的)。括号用于命令替换(如果您需要该功能,则不是可选的)。 $foo${foo} 是相同的。只有当大括号后面的内容被视为变量名的一部分时,才需要大括号。所以 ${foo}bar 是 variable-foo 然后是 string-bar 但 $foobar 是 variable-foobar。
  • 通过shellcheck.net 运行您的代码并修复它抱怨的问题。不过,sn-p 在这方面相当不错。我个人不会建议为then 和else` 使用与iffi 不同的缩进级别,我认为这只会令人困惑。就我个人而言,我也使用 if [ ...]; then 而不是将 then 放在自己的行中。
  • 不喜欢你的缩进风格

标签: bash if-statement logic


【解决方案1】:

整体cmets

  • 嵌套的“if”没有问题,但提前退出会更清晰
  • cut 比 awk 便宜,但 read 仍然更便宜
  • 使用“[”而不是“[[”的简单字符串相等测试稍微便宜
  • 将错误消息写入 STDERR
  • 使用 read 和
  • 使用函数

简化版

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" 

【讨论】:

  • 使用变量存储错误消息xxxxINSERT-CHECKSUM-HERExxxx也可能有帮助。
  • @RTLinuxSW "${@}" 是什么意思...。我尝试用谷歌搜索它,但没有运气。另外,我通过 shellcheck.net 运行了代码……出色的工具!修复了几个小错误,谢谢!
  • "${@}" 在 BASH 手册页的“参数”部分,“特殊参数”小节中进行了解释。该段落中描述了双引号的重要性。
猜你喜欢
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
相关资源
最近更新 更多