如何构建bash代码以便更容易跟踪条件?

时间:2017-05-24 14:46:12

标签: bash ubuntu if-statement wizard

我正在制作一个安装向导,但是我有很多IF语句,它让我感到困惑,我迷失方向,尤其是当我尝试修复我的脚本错误的东西时。怎么预防这个?这是我的剧本:

正如你所看到的,如果有IF声明,我会有很多。我无法跟踪它们。有没有办法像HTML一样标记或最小化它们? 我正在使用Atom Text编辑器。

或者有没有办法减少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 $0
        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

1 个答案:

答案 0 :(得分:2)

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

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

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

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

当匹配3个或更多值并且在某些情况下匹配2个或更多时,案例块通常更易读:

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