使用 Bash 变量支持扩展 - {0..$foo}

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9337489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:35:13  来源:igfitidea点击:

Brace expansion with a Bash variable - {0..$foo}

bashbrace-expansion

提问by xref

WEEKS_TO_SAVE=4
mkdir -p weekly.{0..$WEEKS_TO_SAVE}

gives me a folder called weekly.{0..4}

给我一个名为每周的文件夹。{0..4}

Is there a secret to curly brace expansion while creating folders I'm missing?

在创建我丢失的文件夹时是否有花括号扩展的秘密?

采纳答案by kev

bashdoes brace expansionbefore variable expansion, so you get weekly.{0..4}.
Because the result is predictable and safe(Don't trust user input), you can use evalin your case:

bashbrace expansion之前没有variable expansion,所以你得到weekly.{0..4}
因为结果是可预测且安全的(不要相信用户输入),所以您可以eval在您的情况下使用:

$ WEEKS_TO_SAVE=4
$ eval "mkdir -p weekly.{0..$((WEEKS_TO_SAVE))}"

note:

注意

  1. evalis evil
  2. use evalcarefully
  1. eval是邪恶的
  2. eval小心使用

Here, $((..))is used to force the variable to be evaluated as an integer expression.

在这里,$((..))用于强制将变量计算为整数表达式。

回答by anubhava

Curly braces don't support variables in BASH, you can do this:

花括号不支持 BASH 中的变量,你可以这样做:

 for (( c=0; c<=WEEKS_TO_SAVE; c++ ))
 do
    mkdir -p weekly.${c}
 done

回答by jfg956

Another way of doing it without eval and calling mkdir only once:

另一种不使用 eval 并且只调用一次 mkdir 的方法:

WEEKS_TO_SAVE=4
mkdir -p $(seq -f "weekly.%.0f" 0 $WEEKS_TO_SAVE)

回答by amit_g

Brace expansiondoes not support it. You will have to do it using a loop.

大括号扩展不支持它。你将不得不使用循环来做到这一点。

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. To avoid conflicts with parameter expansion, the string ‘${' is not considered eligible for brace expansion

大括号扩展在任何其他扩展之前执行,并且其他扩展所特有的任何字符都保留在结果中。它是严格的文本。Bash 不对扩展的上下文或大括号之间的文本应用任何句法解释。为避免与参数扩展冲突,字符串 '${' 不被视为符合大括号扩展的条件

.

.

回答by SiegeX

If you happen to have zshinstalled on your box, your code as written willwork with Z-shell if you use #!/bin/zshas your interpreter:

如果您碰巧zsh安装在您的机器上,如果您将其用作解释器,那么您编写的代码与 Z-shell 一起使用#!/bin/zsh

Example

例子

$ WEEKS_TO_SAVE=4
$ echo {0..$WEEKS_TO_SAVE}
0 1 2 3 4