【问题标题】:access modifiers in bashbash 中的访问修饰符
【发布时间】:2021-06-24 02:46:28
【问题描述】:

假设我有一个 bash 脚本,我希望一些变量在获取时出现,而其他变量只能从脚本中访问(函数和变量)。实现这一目标的惯例是什么?

【问题讨论】:

  • 你试过 bash 的 local 内置函数吗?见help local
  • 是的,采购后价值仍然出现

标签: bash import access-modifiers


【解决方案1】:

假设test.sh 是您的 bash 脚本。

你可以做的是提取所有常见的项目并将它们放在common.sh中,可以由其他脚本获取。

【讨论】:

    【解决方案2】:

    BASH_SOURCE 数组可以帮助您:

    考虑一下这个脚本,source.sh

    #!/bin/bash
    if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
        # this code is run when the script is _executed_
        foo=bar
    
        privFunc() { echo "running as a script"; }
    
        main() {
            privFunc
            publicFunc
        }
    fi
    
    # this code is run when script is executed or sourced
    answer=42
    publicFunc() { echo "Hello, world!"; }
    
    echo "$0 - ${BASH_SOURCE[0]}"
    
    [[ ${BASH_SOURCE[0]} == "$0" ]] && main
    

    运行它:

    $ bash source.sh
    source.sh - source.sh
    running as a script
    Hello, world!
    

    采购:

    $ source source.sh
    bash - source.sh
    $ declare -p answer
    declare -- answer="42"
    $ declare -p foo
    bash: declare: foo: not found
    $ publicFunc
    Hello, world!
    $ privFunc
    bash: privFunc: command not found
    $ main
    bash: main: command not found
    

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 2015-04-11
      • 1970-01-01
      • 2017-08-18
      • 2013-05-25
      • 2015-04-09
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多