代码之家  ›  专栏  ›  技术社区  ›  kittygirl

如何基于子函数返回值退出父函数?

  •  0
  • kittygirl  · 技术社区  · 5 年前
    #!/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 .
    怎么做?

    提前谢谢!

    1 回复  |  直到 5 年前
        1
  •  1
  •   KamilCuk    5 年前

    处理函数的返回值怎么样?

    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 没有 地方的 单词