为何Bash中${##parameter}等始终返回0而非抛出替换错误?
${##parameter} Returns 0 Instead of Throwing an Error Great question! This behavior boils down to how Bash parses parameter expansions and handles undefined/invalid variable names. Let's break it down step by step:
First, recall what
${#parameter}does: This is Bash's standard parameter expansion to get the length of the value stored inparameter. Since you mentioned it returns 5, that meansparameteris defined and holds a string 5 characters long—totally expected.How Bash parses
${##parameter}: When you add extra#characters at the start, Bash doesn't treat this as broken syntax. Instead, it interprets the first#as the length operator, and the remaining#parameteras the name of the variable whose length you're trying to calculate. In other words,${##parameter}is equivalent to${# #parameter}(the space is just for clarity).Why
#parameterresolves to an empty string: Bash has strict rules for variable names—they must start with a letter or underscore, and can only contain letters, numbers, and underscores.#parameterstarts with a#, making it an invalid variable name (you can't even define a variable with that name in Bash).In default Bash settings (without
set -uenabled), referencing an undefined or invalid variable name automatically expands to an empty string. The length of an empty string is 0, which is why you get that result.Why no syntax error is thrown: This isn't a syntax mistake—Bash recognizes
${#name}as a valid parameter expansion structure, regardless of whethernameis a valid/defined variable. Syntax errors only occur when the expansion itself is malformed (like missing the closing}, or using an operator in a nonsensical context such as${@#}without a matching pattern).
Let's test this with a quick example to confirm:
# Define our original variable parameter="hello" echo ${#parameter} # Outputs 5, as expected # Try the double-hash version echo ${##parameter} # Outputs 0 # Even triple hash works the same way echo ${###parameter} # Also outputs 0
If you enable set -u (which makes Bash treat undefined variables as errors), you'll see a different result:
set -u echo ${##parameter} # Throws: bash: #parameter: unbound variable
This confirms that the issue is just Bash treating the invalid variable name as undefined/empty by default.
内容的提问来源于stack exchange,提问作者Glitch

