我如何构建 bash 代码以更轻松地跟踪条件?

How can I structure bash code to make it easier to track conditionals?

我正在制作一个安装向导,但是我有很多 IF 语句,它一直让我感到困惑,我迷失了方向,尤其是当我试图修复我的脚本中的错误时。如何防止这种情况?这是我的脚本:

如您所见,我有很多 IF 语句。我无法跟踪所有这些。有没有办法喜欢标记或最小化它们,比如 HTML? 我正在使用 Atom 文本编辑器。

或者有没有办法减少 IF 语句?

#!/bin/bash

# Author: GlitchyShadowZ

# Name: NJDTL Install Wizard 1.0

# Date of Last Update:

# Date of LEGACY (Initial Release):
clear
echo "Would you like to start the NJDTL Install Wizard? [y/n]"
read startYN
if [ $startYN == y ]
  then
      echo "Starting Install Wizard. . ."
      mkdir ~/.NJDTL
    fi
    if [ $startYN == n ]
      then
          echo "Are you sure you want to cancel the Install Wizard? [y/n]"
          read CancelConfirm
          if [ $CancelConfirm == y ]
            then
                echo "Cancelling Install. . ."
                exit
              fi
          if [ $CancelConfirm == n ]
            then
                echo "Chose "n". Continuing Installation. . ."
                exec [=11=]
        fi
      fi

[Loading Screen removed for the purpose of this post]

if ! [ -d ~/sbin ]
then
echo "A Bin folder in /home/ is required for this program. Create one? [y/n]"
read BinChoice
  if [ $BinChoice = y ]
    then
      mkdir ~/testbin
    fi
    if [ $BinChoice = n ]
  then
    echo "Without a Bin Folder NJDTL Will not work. Cancelling Install."
  fi

else
  echo "bin folder existent. Continuing Install. . ."
fi
fi

条件句的一个常见用法是将下一个关键字放在同一行:

if [ $startYN == y ]; then
  ...

$startYN == n 应该在 elif 语句中($CancelConfirm == n 也是如此):

if [ "$startYN" == y ]; then
  ...
elif [ "$startYN" == n ]; then
  ..
fi

当匹配 3 个或更多值,在某些情况下匹配 2 个或更多值时,case 块通常更具可读性:

case "$startYN" in
  'y')
    ...
    ;;
  'n')
    ...
    case "$CancelConfirm" in
      'y')
        ...
        ;;
      'n')
        ...
        ;;
    esac
    ;;
esac