【发布时间】: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` 使用与if和fi不同的缩进级别,我认为这只会令人困惑。就我个人而言,我也使用if [ ...]; then而不是将 then 放在自己的行中。 -
不喜欢你的缩进风格
标签: bash if-statement logic