gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:01:30 25 4
gpt4 key购买 nike

我正在制作一个安装向导,但是我有很多 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 $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

最佳答案

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

if [ $startYN == y ]; then
...
$startYN == n应该在一个 elif 语句中(对于 $CancelConfirm == n 也是如此):
if [ "$startYN" == y ]; then
...
elif [ "$startYN" == n ]; then
..
fi

当匹配 3 个或更多值(在某些情况下为 2 个或更多)时,case block 通常更具可读性:
case "$startYN" in
'y')
...
;;
'n')
...
case "$CancelConfirm" in
'y')
...
;;
'n')
...
;;
esac
;;
esac

关于bash - 如何构建 bash 代码以更轻松地跟踪条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44161782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com