bash 中的访问修饰符
access modifiers in bash
假设我有一个 bash 脚本,我希望一些变量在获取时出现,而其他变量只能从脚本中访问(函数和变量)。实现这一目标的惯例是什么?
假设 test.sh
是您的 bash 脚本。
你可以做的是提取所有常见项目并将它们放入 common.sh
中,其他脚本可以获取这些项目。
BASH_SOURCE
数组在此处帮助您:
考虑这个脚本,source.sh
#!/bin/bash
if [[ ${BASH_SOURCE[0]} == "[=10=]" ]]; 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 "[=10=] - ${BASH_SOURCE[0]}"
[[ ${BASH_SOURCE[0]} == "[=10=]" ]] && 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
假设我有一个 bash 脚本,我希望一些变量在获取时出现,而其他变量只能从脚本中访问(函数和变量)。实现这一目标的惯例是什么?
假设 test.sh
是您的 bash 脚本。
你可以做的是提取所有常见项目并将它们放入 common.sh
中,其他脚本可以获取这些项目。
BASH_SOURCE
数组在此处帮助您:
考虑这个脚本,source.sh
#!/bin/bash
if [[ ${BASH_SOURCE[0]} == "[=10=]" ]]; 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 "[=10=] - ${BASH_SOURCE[0]}"
[[ ${BASH_SOURCE[0]} == "[=10=]" ]] && 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