6 Jan 2024 |
vigress7 | https://gitlab.archlinux.org/archlinux/packaging/packages/prettier/-/blob/main/PKGBUILD?ref_type=heads#L34 | 17:39:07 |
vigress7 | Wait, the local actually breaks it | 17:49:42 |
vigress7 | Elsie aight help me out here, how do scopes work in Bash | 17:56:32 |
TwilightBlood#4432 | so | 17:56:45 |
TwilightBlood#4432 | export foo
local foo | 17:56:53 |
TwilightBlood#4432 | * export foo
local foo
declare -n foo | 17:57:03 |
TwilightBlood#4432 | those are the 3 possible variable scopes | 17:57:09 |
TwilightBlood#4432 | and for functions you have: | 17:57:11 |
TwilightBlood#4432 | function foo() {}
function foo() () | 17:57:18 |
TwilightBlood#4432 | export can be used inside functions ({} ) to leak out vars, and when used outside a function will be able to leak into child processes | 17:57:59 |
TwilightBlood#4432 | local can be used inside functions ({} and () ) to prevent a variable from inside from leaking outside | 17:58:22 |
TwilightBlood#4432 | declare -n makes a local variable binded to an external variable | 17:58:38 |
TwilightBlood#4432 | and for functions: | 17:58:52 |
TwilightBlood#4432 | oh wait before that | 17:58:55 |
TwilightBlood#4432 | declare -n cannot have the name of an already declared variable | 17:59:11 |
TwilightBlood#4432 | local can only be used inside functions | 17:59:22 |
TwilightBlood#4432 | same for declare -n | 17:59:28 |
TwilightBlood#4432 | export can be used anywhere | 17:59:33 |
TwilightBlood#4432 | foo() {} creates a function that can leak into outside foo() () creates a subshell function so nothing can be leaked | 17:59:53 |
vigress7 | So if I export foo inside bar() and then need to use it in baz() , I need declare -n foo for baz() to inherit foo ? | 18:01:51 |
TwilightBlood#4432 | oh nono that's not how declare -n works | 18:02:14 |
TwilightBlood#4432 | are you familiar with C pointers? | 18:02:21 |
vigress7 | Sorta | 18:02:28 |
TwilightBlood#4432 | function change_foo() {
declare -n bar="${1}"
bar=0
}
foo=71
echo "${foo}" # Prints 71
change_foo foo
echo "${foo}" # Prints 0 | 18:03:40 |
TwilightBlood#4432 | or lemme also get a real example in pacstall | 18:03:42 |
TwilightBlood#4432 | It's more useful for arrays | 18:03:52 |
TwilightBlood#4432 | https://github.com/pacstall/pacstall/blob/develop/misc/scripts/dep-tree.sh | 18:03:58 |
TwilightBlood#4432 | oh and local -n and declare -n are the same iirc | 18:04:15 |
TwilightBlood#4432 | and a funny thing about this is that you can do: | 18:06:11 |
TwilightBlood#4432 | function foo() ((bar=0)) | 18:06:18 |