local variable and asterisk
I´ve declared a LOCAL variable (a) inside a function that receives the value of first parameter (${1}). When I call it with a with an asterisk in开发者_运维百科 first parameter´s content, the value assignment had a different treatment. Why?
# function_name () { local a="${1}"; echo $a; }
# set -xv && function_name "param_1_*" && set +xv
set -xv && function_name "param_1_*" && set +xv
+ set -xv
+ function_name 'param_1_*'
+ local 'a=param_1_*'
+ echo 'param_1_*'
param_1_*
+ set +xv
NOTE: + local 'a=param_1_*' <-- See? the quote is inserted before the variable name "a"
# function_name () { a="${1}"; echo $a; }
# set -xv && function_name "param_1_*" && set +xv
+ function_name 'param_1_*'
+ a='param_1_*'
+ echo 'param_1_*'
param_1_*
+ set +xv
NOTE: + a='param_1_*' <-- On this case, the quote is inserted after the equal signal
They're being displayed differently by bash's -x mode, but that doesn't mean bash is treating them differently. What's happening here is that when bash executes local a="${1}"
, it parses it into some internal representation (something more complicated than a string), substitutes the first parameter into that, and then notices that -x mode is active. So what it does is take that internal representation, and un-parses it into a command you could type in to get the same effect. In general, there will be a number of ways to type in a command that'd produce the same effect (i.e. the internal representation), and it chooses one of these. It could print any of the following:
+ local a='param_1_*'
+ local 'a=param_1_*'
+ local $'a=param_1_*'
+ local a=param_1_"*"
+ local a=param_1_\*
... or any of a number of other possibilities. Its choice may not be the one you'd expect, but it's a perfectly valid way of typing in the "same" command.
BTW, as @Rob said, there is a difference in that a='param_1_*'
and 'a=param_1_*'
are not equivalent commands, while local a='param_1_*'
and local 'a=param_1_*'
are equivalent. This is because with the local command, the assignment is essentially a parameter, and quoting around it doesn't matter as much as with a standalone assignment. Thus, when displaying a="${1}"
, it could print any of:
+ a='param_1_*'
+ a="param_1_*"
+ a=param_1_$'*'
+ a=param_1_\*
but not any of these:
+ 'a=param_1_*'
+ "a=param_1_*"
+ $'a=param_1_*'
I don't think the asterisk is the difference. In your two functions, one is declaring a local and one is setting a shell variable. In the first case you're passing a=param_1_*
as an argument to the local builtin (and the shell doesn't care that one of those characters is an *
or an =
), but in the second the shell is parsing the a=foo
into its components. In the first case, it makes sense to put quotation marks around the entire argument, which is a=param_1_*
, but it doesn't make sense in the second, since you couldn't really type 'a=param_1_*'
at a shell prompt and expect the shell to set the a variable.
精彩评论