Bash - Return value from subscript to parent script

后端 未结 3 2098
心在旅途
心在旅途 2021-01-31 14:46

I have two Bash scripts. The parent scripts calls the subscript to perform some actions and return a value. How can I return a value from the subscript to the parent script? Add

3条回答
  •  眼角桃花
    2021-01-31 15:27

    Here is another way to return a text value from a child script using a temporary file. Create a tmp file in the parent_script and pass it to the child_script. I prefer this way over parsing output from the script

    Parent

    #!/bin/bash
    # parent_script
    text_from_child_script=`/bin/mktemp`
    child_script -l $text_from_child_script
    value_from_child=`cat $text_from_child_script`
    echo "Child value returned \"$value_from_child\""
    rm -f $text_from_child_script
    exit 0
    

    Child

    #!/bin/bash
    # child_script
    # process -l parm for tmp file
    
    while getopts "l:" OPT
    do
        case $OPT in
          l) answer_file="${OPTARG}"
             ;;
        esac
    done
    
    read -p "What is your name? " name
    
    echo $name > $answer_file
    
    exit 0
    

提交回复
热议问题