通过遍历Bash中的数组循环创建文件

时间:2019-03-19 07:53:24

标签: arrays bash loops

我在Bash脚本的逻辑上遇到了一个错误。我有一个包含数字,大写和小写值的数组,我试图循环并根据该数组值创建文件。所有数字文件都会创建,小写文件也会创建,但是大写文件不会创建。

我尝试使用bash +x scriptname.sh调试脚本,这表明已创建文件,但它们未出现在目录中。我还做了一个echo "${LETTERNUM[k]}",它表明循环在迭代正确的时间。

另一个问题,是否有更清洁的方法来做到这一点?我觉得重复调用${LETTERNUM[k]}可能不是最好的方法-是否有其他/更好的方法来打印8次?而且我敢肯定还有其他方法,例如touch{a..z}来生成文件,但是我需要在脚本的另一部分使用数组。

#!/bin/bash
declare -a LETTERNUM=("a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0");

for (( k=0; k<=61; k++ ))
do

     > "${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}${LETTERNUM[k]}".txt
done

3 个答案:

答案 0 :(得分:0)

尝试以下操作,直接遍历数组并使用touch命令创建文件:

#!/bin/bash
declare -a LETTERNUM=("a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0");

for i in "${LETTERNUM[@]}"
do
    touch $i.txt
done

答案 1 :(得分:0)

我只是对其进行了更改,以使文件名的生成更加简洁。关于大写字母,由于所有文件(包括大写字母)都已在我的系统上正确生成,因此我无法复制该错误。

#!/bin/bash

declare -a LETTERNUM=("a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0");

for i in "${LETTERNUM[@]}"; do
    touch $(printf "${i}%.0s" {1..8})".txt"
done

答案 2 :(得分:0)

如果我试图将所有大写和小写字母和数字[0-9]用作索引数组的元素,则只使用包含所需字符的字符串,遍历长度并使用字符串索引,将每个字符添加到数组中。有一些实用程序可以创建字符序列,但是不能保证没有安装。

使用C风格的for循环的快速方法是:

## string containing all characters
c=abcdefghijklmnopqrstuvwxyzABCDEFGHINJLMNOPQRSTUVWXYZ0123456789

## loop over each char
for ((i = 0; i < ${#c}; i++)); do
    a+=( ${c:i:1} )     ## add each char as array element
done
declare -p a   ## output filled array to confirm

您可以将鼠标粘贴/粘贴到终端中以查看形成的数组:

$ c=abcdefghijklmnopqrstuvwxyzABCDEFGHINJLMNOPQRSTUVWXYZ0123456789
> for ((i = 0; i < ${#c}; i++)); do
>     a+=( ${c:i:1} )
> done
> declare -p a
declare -a a='([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g" [7]="h" 
[8]="i" [9]="j" [10]="k" [11]="l" [12]="m" [13]="n" [14]="o" [15]="p" 
[16]="q" [17]="r" [18]="s" [19]="t" [20]="u" [21]="v" [22]="w" [23]="x" 
[24]="y" [25]="z" [26]="A" [27]="B" [28]="C" [29]="D" [30]="E" [31]="F" 
[32]="G" [33]="H" [34]="I" [35]="N" [36]="J" [37]="L" [38]="M" [39]="N" 
[40]="O" [41]="P" [42]="Q" [43]="R" [44]="S" [45]="T" [46]="U" [47]="V" 
[48]="W" [49]="X" [50]="Y" [51]="Z" [52]="0" [53]="1" [54]="2" [55]="3" 
[56]="4" [57]="5" [58]="6" [59]="7" [60]="8" [61]="9")'

可能有许多不同的方式,但是从效率角度来看,内置的字符串索引参数扩展可能与61个字符的扩展速度差不多。