bash bash脚本循环多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18773160/
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
bash script loop multiple variables
提问by user654320
I am trying to write something like following
我正在尝试编写如下内容
for i in {a..z} && j in {1..26}
do
echo "/dev/sd"$i"1 /disk$j ext4 noatime 1 1" >> test
done
Of course this is not correct syntax. Can someone please help me with correct syntax for doing this?
当然,这不是正确的语法。有人可以帮助我使用正确的语法来执行此操作吗?
回答by Guna
To be generic, you can use 'length' as shown below.
为了通用,您可以使用“长度”,如下所示。
#!/bin/bash
# Define the arrays
array1=("a" "b" "c" "d")
array2=("w" "x" "y" "z")
# get the length of the arrays
length=${#array1[@]}
# do the loop
for ((i=0;i<=$length;i++)); do
echo -e "${array1[$i]} : ${array2[$i]}"
done
You can also assign the array like the following
您还可以像下面这样分配数组
array1=`awk -F" " ' == "CLIENT" { print }' clientserver.lst`
回答by konsolebox
You can use arrays for that:
您可以为此使用数组:
A=({a..z}) B=({1..26})
for (( I = 0; I < 26; ++I )); do
echo "/dev/sd${A[I]} /disk${B[I]} ext4 noatime 1 1" >> test
done
Example output:
示例输出:
/dev/sda /disk1 ext4 noatime 1 1
...
/dev/sdz /disk26 ext4 noatime 1 1
Update:
更新:
As suggested you could just use the index for values of B:
正如所建议的,您可以只使用 B 值的索引:
A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
echo "/dev/sd${A[I]} /disk${I} ext4 noatime 1 1" >> test
done
Also you could do some formatting with printf
to get a better output, and cleaner code:
您也可以进行一些格式化printf
以获得更好的输出和更清晰的代码:
A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
printf "%s%20s%15s%15s%4s%2s\n" "/dev/sd${A[I]}" "/disk${I}" ext4 noatime 1 1 >> test
done
Also, if you don't intend to append data to file, but only write once every generated set of lines, just make redirection by block instead:
此外,如果您不打算将数据附加到文件中,而只在每组生成的行中写入一次,则只需按块进行重定向:
A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
printf "%s%20s%15s%15s%4s%2s\n" "/dev/sd${A[I]}" "/disk${I}" ext4 noatime 1 1
done > test