How do you return to a sourced bash script?

后端 未结 3 2140
后悔当初
后悔当初 2020-12-01 13:40

I use "source" inside a bash script, as follows:

#!/bin/bash
source someneatscriptthatendsprematurely.sh

I would like to exit from

3条回答
  •  天涯浪人
    2020-12-01 14:15

    I had the same problem just now

    I realized that adding a checker function and returning that will not also return the function on its caller for example.

    On bash_functions

    function install_packer_linux() {
      check_wget && check_unzip
      wget https://releases.hashicorp.com/packer/1.1.2/packer_1.1.2_linux_amd64.zip
      unzip packer_1.1.2_linux_amd64.zip
      mv packer ~/.local/bin
      rm -f packer_1.1.2_linux_amd64.zip
    }
    
    
    function check_unzip() {
      if ! [ -x "$(command -v unzip)" ]; then
        echo "Error: unzip is not installed"
        return 1
      else
        return 0
      fi
    }
    
    function check_wget() {
      if ! [ -x "$(command -v wget)" ]; then
        echo "Error!: wget is not installed"
        return 1
      else
        return 0
      fi
    }
    
    
    $ source ~/.bash_functions
    

    What happens here is since the checkers is the only place its returned so install_packer_linux will still continue

    So you can do two things here. Either keep the current format (function calling another function) as is and evaluate using truthy value then return if the values are not truthy or rewrite the checker on the main installer_packer_linux function

    Truthy:

    function install_packer_linux() {
      check_wget && check_unzip || return
      wget https://releases.hashicorp.com/packer/1.1.2/packer_1.1.2_linux_amd64.zip
      unzip packer_1.1.2_linux_amd64.zip
      mv packer ~/.local/bin
      rm -f packer_1.1.2_linux_amd64.zip
    }
    

    Notice we added || return after the checks and concatenated the checks using && so if not both checks are truthy we return the function

提交回复
热议问题