为什么以下习惯用法在 bash 4.1.0 中不起作用?
if [[ "${FUNCNAME[*]:1/$FUNCNAME/}" != "${FUNCNAME[*]:1}" ]]
这是在上下文中...
function isCircularRef_test () {
#
### Seems like this should work but it does not.
### if [[ "${FUNCNAME[*]:1/$FUNCNAME/}" != "${FUNCNAME[*]:1}" ]]; then ...
### It appears to fail silently and exit the script so neither 'then' nor
### 'else' branch executes.
### Storing the array into a temporary string variable works. Why necessary?
#
printf "%s\n" "VERSION #1"
local _fna="${FUNCNAME[*]:1}"
if [[ "${_fna/$FUNCNAME/}" != "${_fna}" ]]
then
printf "%s\n" "IS circular reference"
else
printf "%s\n" "IS not circular reference"
fi
#
printf "%s\n" "VERSION #2"
if [[ "${FUNCNAME[*]:1/$FUNCNAME/}" != "${FUNCNAME[*]:1}" ]]
then
printf "%s\n" "IS circular reference"
else
printf "%s\n" "IS not circular reference"
fi
}
输出是...
VERSION #1
IS not circular reference
VERSION #2
答案1
这文档shell参数扩展表示替换的语法是:
${parameter/pattern/string}
请注意,第一部分是parameter
,而不是另一个包含参数扩展的表达式。所有其他扩展修饰符也是如此。您必须分两步完成:
func1=${FUNCNAME:1}
if [[ ${func1/$FUNCNAME/} != ${func1} ]]
答案2
正如您所说,它不喜欢在同一表达式中使用:index
和修饰符:/pattern/
./t.sh: line 19: FUNCNAME[*]: 1/isCircularRef_test/: division by 0 (error token is "/")