Reputation:
I have an alias:
alias local='if [ -z "${FUNCNAME[0]}" ]; then builtin local; fi; declare'
Which I want to use to redirect local commands into my modified declare function, which then can declare the variables, and only use the builtin local
to get error messages if outside an function.
The alias has an output of (using set -x):
+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
+ declare
Right now it executes the declare
anyways and I would like it to exit if the check fails. I can't use a function for this.
So far I've tried return, break and exit (exit not here for obvious reasons):
alias 'local=if [ -z "${FUNCNAME[0]}" ]; then builtin local; return 1; break; fi; declare'
+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
+ return 1
-bash: return: can only `return' from a function or sourced script
+ break
-bash: break: only meaningful in a `for', `while', or `until' loop
+ declare
Example:
# When outside an function
local some_var=val
+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
# That's it
# When inside an function func
local some_var=val
+ '[' -z func ']'
+ declare some_var=val
# Uses my modified declare function
Upvotes: 2
Views: 108
Reputation:
As builtin local
is only used to get the error message, this will work:
alias local='builtin local 2>&1 >/dev/null; [ -n "${FUNCNAME[0]}" ] && declare'
It will always print only the error, if not inside a function, but won't print out all the local variables if inside one:
$> func () { local var2=foo; local var=bar; echo $var; }
$> func
+ func
+ builtin local
+ '[' -n func ']'
+ declare var2=foo
+ builtin local
+ '[' -n func ']'
+ declare var=bar
+ echo bar
bar
This way local gets replaced by declare, which then I can modify with a wrapper.
Upvotes: 1
Reputation: 42999
Not sure why you need such an alias. In any case, don't use an alias for this. Use a function instead:
local() {
if [ -z "${FUNCNAME[0]}" ]; then
builtin local "$@"
else
declare -g "$@" # -g (for global) is necessary - otherwise variable set by declare would be local to the function
fi
}
Upvotes: 1