You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Bash中${##parameter}等始终返回0而非抛出替换错误?

Why ${##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 in parameter. Since you mentioned it returns 5, that means parameter is 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 #parameter as 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 #parameter resolves 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. #parameter starts 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 -u enabled), 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 whether name is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:18:10