【问题标题】:Bash dynamic variables conflictBash 动态变量冲突
【发布时间】:2013-10-29 16:44:26
【问题描述】:

我在下面的代码中遇到问题,set -x 告诉我正在分配变量,但尝试在此循环之外回显它们似乎不起作用?

          export "ex_$x"=$(git rev-parse HEAD | cut -c1-10)

      done
    ((used++))

    echo $ex_render
    echo $ex_storage

    exit # =/

    php -f "${cdir}/../public/bootstrap.php" -- "${line}" "${ex_render}" "${ex_storage}"

【问题讨论】:

  • 您可以发布其余的脚本吗?有可能你的 while 循环是 accidentally creating a subshell,此时循环的主体正在使用不同的变量集在不同的环境中运行。
  • 使用数组,而不是动态生成的变量名。
  • @chepner 好建议,如果他有 bash 4。
  • 它被标记为这样,但甚至不清楚他需要一个关联数组,或者变量的名称很重要(它们似乎作为参数传递给 PHP 脚本,而不是通过环境继承)。
  • @JeffBowman 是的,我在 pastebin.com/LunQcxgq 有一个完整的 pastebin 转储文件

标签: bash while-loop dynamically-generated bash4


【解决方案1】:

看起来你的代码被截断了,但它听起来像the classic pipe-to-read problem。

$ echo hi | read x
$ echo $x
$ # Nothing!
$ read x <<< hi
$ echo $x
hi

基本上,管道创建一个隐式子shell。要避免它,请避免使用管道:

while read foo; do things; done < <(process substitution)

或显式创建子shell,以便您可以控制范围:

inputcommand | ( while read foo; do things; done;
  # variables still assigned as long as you're in the subshell
)

【讨论】:

  • 那是正确的,我正在输入,让我快速测试一下,以确保它在接受之前可以正常工作
  • 工作完美,+1 并被接受。谢谢你。注意:我用你的第二个管道,因为我在做echo -e "render\nstorage" | ( while read x; do export ex_$x='foo'; done;
  • @ehime 仍然没有必要。你可以只做&lt;&lt;&lt; $'render\nstorage' while read … 而没有管道。
  • 这看起来像是不必要地使用循环。 ex_render='foo'; ex_storage='foo' 更清晰,更不容易出错。
  • @ehime 你只是把这里的字符串放错了地方。您可以将其放在while 关键字之前或done 之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
相关资源
最近更新 更多