Shell:间接扩展会引发不良替换,我是Windows,但不是Mac

问题描述

这是我正在谈论的脚本

#!/bin/bash
_sv="77777777777777777a"
if [ -n "${!_sv}" ]; then
  echo "the value is there"
  ${echo} "${!sv}"
elif [ -n "${!1}" ]; then
  echo "${!1}"
else
  echo "False"
fi

当我在Windows10的GNU bash中使用 sh test.sh 或在 bash test.sh 中运行它时(使用Cmder),这给我带来了麻烦替换错误

dir_1/test.sh: line 2: 77777777777777777a: bad substitution

但是,只要且仅当变量为纯字母或数字形式时,同一脚本在macOS终端外壳和Windows10中运行就不会出现任何错误

重要:如果_sv值为字母数字,则替换错误错误

请帮助!

解决方法

这是预期的行为。您收到此错误消息是因为您要扩展的名称不是有效的变量名称。

这张支票是introduced in Bash 4.4 commit a0c0a00fc419b7

@@ -5926,6 +6661,16 @@ parameter_brace_expand_indir (name,var_is_special,quoted,quoted_dollar_atp,c
   if (t == 0)
     return (WORD_DESC *)NULL;

+  if (valid_brace_expansion_word (t,SPECIAL_VAR (t,0)) == 0)
+    {
+      report_error (_("%s: bad substitution"),t);
+      free (t);
+      w = alloc_word_desc ();
+      w->word = &expand_param_error;
+      w->flags = 0;
+      return (w);
+    }
+
   w = parameter_brace_expand_word (t,SPECIAL_VAR(t,0),0);
   free (t);

以前的版本将其扩展为空字符串。这包括macOS的Bash 3.2。