Bash - how to make arithmetic expansion in range braces?

一曲冷凌霜 提交于 2021-02-11 07:00:09

问题


I want to do this: for i in {1.."$((2**3))"}; do echo "$i"; done

But that would output {1..8}, which I want to execute, not output. How to?


回答1:


You can't do in like that in bash, brace expansion happens before variable does. A c-style for loop can be an alternative.

for ((i = 1; i <= 2**3; i++)); do printf '%d ' "$i"; done

... Or if you really want to do the brace expansion use eval which is not advised to use but it is the only way...

eval echo {1..$((2**3))}
  • See the local bash manual for the order of expansion PAGER='less +/^EXPANSION' man bash and the online manual (thanks to @Freddy) https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html

  • See eval in the local bash manual PAGER='less +/^[[:blank:]]*eval\ ' man bash




回答2:


You could to use seq instead of range braces:

for i in $(seq 1 $((2**3))); do echo "$i"; done


来源:https://stackoverflow.com/questions/61398661/bash-how-to-make-arithmetic-expansion-in-range-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!