首页 > 解决方案 > 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中使用sh test.shbash test.shbash运行它(使用 Cmder)时,它给了我一个错误的替换错误

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

但是,当且仅当变量是纯字母或数字时,相同的脚本在 macOS 终端 shell 和 Windows10 中运行时不会出现任何错误。

重要提示:如果 _sv 值是字母数字,则会给出错误的替换错误。

请帮忙!

标签: bashshellwindows-10

解决方案


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

这个检查是在 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), quoted, 0, 0);
   free (t);

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


推荐阅读