如何在没有退出程序的情况下在bash中退出if语句?

时间:2015-06-16 17:05:09

标签: bash terminal

重写这个问题以避免更多的downvotes,因为我删除它为时已晚:

我正在编写一个脚本,要求用户进行确认,并在sourcing之前写一些其他脚本。为了简化代码,假设有两个脚本可能是sourced,但我希望用户要么source无,要么只有一个脚本 - 而不是两者。我试图使用if true source-script else exit形式的语句,因为我退出if语句,但是整个脚本也没有机会必要的清理。最初,我的脚本看起来像这样:

echo "This script might do something terrible to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
    source "terrible_script.sh"
    # want some way to ensure that we don't prompt the user about the next script
    # don't want to just exit if the response is 'n' because we have to do cleanup
fi

echo "This script might do something really good to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
    source "good_script.sh"
fi

# do cleanup here
# regardless of whether or not any scripts were sourced

@ charles-duffy提供了答案 - 只需将提示包装在一个函数中。类似的东西:

function badscript() {
    echo "This script might do something terrible to your computer."
    read -p "Do you wish to continue? (y/[n]) " -n 1;
    echo
    if ! [[ $REPLY =~ ^[Yy]$ ]]
    then
        source "terrible_script.sh"
        return 0
    fi
}

function goodscript() {
    echo "This script might do something really good to your computer."
    read -p "Do you wish to continue? (y/[n]) " -n 1;
    echo
    if ! [[ $REPLY =~ ^[Yy]$ ]]
    then
        source "good_script.sh"
    fi
}

if ! badscript
then
    goodscript
fi

# cleanup code here

3 个答案:

答案 0 :(得分:7)

首先:不要做任何这些。以其他方式构建您的程序。如果你向我们描述为什么你认为你需要这种行为,我们可能会告诉你如何实现它。

回答问题:如果你将一个块包裹在一个循环中,你可以使用break提前退出:

for _ in once; do
  if true; then
    echo "in the loop"
    break
    echo "not reached"
  fi
done
echo "this is reached"

或者,您可以使用函数,并return提前退出:

myfunc() {
  if true; then
    echo "in the loop"
    return
  fi
  echo "unreached"
}
myfunc
echo "this is reached"

或者,您可以将循环包装在子shell中(尽管这会阻止它执行其他操作,例如影响子shell外部代码的变量赋值):

(if true; then
   echo "in the block"
   exit
   echo "unreached"
 fi)
echo "this is reached."

答案 1 :(得分:0)

只需删除exit即可。它将打印if if语句然后打印你好。

答案 2 :(得分:0)

为什么要打印exit。如果你想要退出循环,只需删除exit及其下面的所有代码(如果存在),因为它不会运行。

如果您打算使用循环并想要退出循环,请使用break退出循环。