代码之家  ›  专栏  ›  技术社区  ›  Toolbox

Bash-如何循环变量的最后一位

  •  0
  • Toolbox  · 技术社区  · 6 年前

    我正在尝试自动创建文件夹。每个文件夹的文件名开头都应该有一个数字(按for循环[$i]增加)。另外,文件夹名称的其余部分应该由构造为[folder_x]的变量来构建,其中[x]应该也由循环来提升。

    更具体地说。 如何构建一个由for循环[$i]和一个被调用的变量组合而成的字符串,但最后还应该使用[$i]?

    有关更多详细信息,请参见以下内容:

    #!/bin/bash
    
    # Variables to be used
    folder_1=1-folderOne
    folder_2=2-folderTwo
    folder_3=3-folderThree
    
    # This is the folder names that should be created:
      # mkdir /tmp2/1-folderOne
      # mkdir /tmp2/2-folderTwo
      # mkdir /tmp2/3-folderThree
    
    # The for loop should combine the [$i] and above [folder_x],
    # where the [x] should also be increased by the loop.
    # Below is what i have right now:
    # Note! The text "created-by-forloop" is just dummy text,
    # and should be replace by the real solution.
    
    
    for i in 1 2 3
    do
      if [ ! -d /tmp2/$i-created-by-forloop ]; then
        mkdir -p /tmp2/$i-created-by-forloop;
      fi
    done
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   choroba    6 年前

    使用名称数组,而不是每个名称的不同变量:

    numbers=(One Two Three)
    for i in "${!numbers[@]}" ; do
        mkdir /tmp2/$((i+1))-folder"${numbers[i]}"
    done
    

    循环在数组的索引上迭代$i。我们需要将1添加到索引中,因为数组是从零开始的,但是我们希望文件的编号从1开始,而不是从0开始。