我编写了一个脚本,其中有一些嵌套的 if 语句。
if [ choice = "1" ]; then
if [ $package == *".tar.gz" ]; then //Could not find fi for this if
tar -zxvf folder.tar.gz
if [ $package == *".tar.bz2" ]; then
tar -xvfj folder.tar.bz2
./configure
make
make install
elif [ choice = "2" ]; then
dpkg -i package.deb
fi
//Expected fi
已写出我在脚本中遇到 fi 错误的位置。
答案1
这是您想要使用的典型情况case
:
case $choice in
(1)
case $package in
(*.tar.gz) tar -zxvf folder.tar.gz;;
(*.tar.bz2) tar -jxvf folder.tar.bz2;;
esac &&
./configure &&
make &&
make install
;;
(2)
dpkg -i package.deb
;;
esac
答案2
条件的基本结构如下:
if [ condition ]; then
dosomething
fi
与其他:
if [ condition ]; then
dosomething
elif [ condition ]; then
dootherthing
else
thelastchancetodosomething
fi
另外,我认为你的代码中的这个条件是错误的:
if [ $package == *".tar.gz" ]; then
tar -zxvf folder.tar.gz
fi
如果我理解正确的话,应该是这样的:
if echo $package | grep -qF ".tar.gz"; then
tar -zxvf $package
fi
哦,并用于#
注释而不是//
.
修复您的示例并改进缩进以使其更加清晰:
if [ choice = "1" ]; then
if echo $package | grep -qF ".tar.gz"; then
tar -zxvf $package
# You need to close previous `if` with a `fi` you want to use another
# `if` here below, but we can use `elif`, so we don't need to close it.
elif echo $package | grep -qF ".tar.bz2"; then
tar -xvfj $package
fi
cd ${package%.*.*} # this removes the .tar.* extension
./configure
make
make install
elif [ choice = "2" ]; then
dpkg -i $package
fi