首页 > 解决方案 > 如何根据子函数返回值退出父函数?

问题描述

#!/bin/bash
#make your own choice,decide which function should be run
set -e
keyin(){
    read -e -p "$1 input y,otherwise input n" local yorn
    if [[ "y" == "$yorn" || "Y" == "$yorn" ]]; then
        return 0
    fi
}
fun1(){
    keyin 'update software no.1'
    echo 'how to exit this function?'
}
fun2(){
keyin 'update software no.2'
echo "fun2 is still running"
}
fun1
fun2

当我运行此脚本并输入y时,我想退出fun1并继续运行fun2
怎么做?

提前致谢!

标签: bash

解决方案


如何处理函数的返回值?

keyin() {
    # read -e -p "$1 input y,otherwise input n" local yorn
    yorn=n
    if [[ "y" == "$yorn" || "Y" == "$yorn" ]]; then
        return 0
    fi
    return 1 # return nonzero in case of error
}

fun1() {
    # handle the return value - in case of non-zero execute custom action
    if ! keyin 'update software no.1'; then
        return
    fi
    echo 'how to exit this function?'
}

fun2() {
    echo "fun2 is still running"
}

fun1
fun2

简单if function; then,让您根据函数的返回值是零还是非零来执行操作。

该语句read .... local yorn读取名为 的变量中的值local。我想你的意思是read .... yorn没有这个local词。


推荐阅读