Bash嵌套循环,日期和数字的混合

时间:2010-10-07 18:31:25

标签: bash for-loop nested-loops

我正在尝试输出一系列具有不同日期和数字的命令。每小时例如。

尝试在循环中执行的输出是:

shell.sh filename<number e.g. between 1-24> <date e.g. 20100928> <number e.g. between 1-24> <id>

所以基本上上面的内容将为每个特定的日期生成24次输出,并带有唯一的4位数ID。

我在考虑使用嵌套循环,因为批号必须是唯一的。

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

目前尚不清楚为什么需要嵌套循环或是否需要迭代一系列日期。但脚本将如下所示:

#!/bin/bash

DAY_FROM=1 # This is a first (starting) day
DAY_TO=24  # This is the last day

DATE=$(date +%Y%m%d) # This is a date we are processing.

id=0 # This is a number for our unique ID generation.
     # It is being incremented for each day.
     # Since this variable is in global scope,
     # it will be unique no matter how many dates you process.
     # If you want unique ID be unique only for date scope,
     # reset it to 0 before processing each date.

# Let's go iterate over all days.
for (( i=$DAY_FROM; i <= $DAY_TO; ++i ))
do
    let ++id # Increment our unique ID number...
    # Print filename, date, number and unique ID.
    # %04d at the end means that we output an integer
    # with 4 digits padded with zeroes if needed.
    printf "%s %s %s %04d\n" "filename$i" "$DATE" "$i" "$id"
done

...输出将如下:

filename1 20101007 1 0001
filename2 20101007 2 0002
filename3 20101007 3 0003
....

希望它有所帮助!

答案 1 :(得分:0)

我想做一个嵌套循环,因为我需要的输出就像:

filename1 20101007 01 0001
filename2 20101007 02 0002
filename3 20101007 03 0003
filename4 20101007 04 0004
filename5 20101007 05 0005
filename6 20101007 06 0006
......... ........ .. ....
to
filename24 20101007 24 0024

filename25 20101008 01 0025

(正如你可以看到一个新的集合开始于另一个日期,这个过程继续进行n个日期迭代)

这就是为什么我在想嵌套循环:-S