时间戳中使用的冒号给出了变量语法错误

时间:2016-08-31 16:41:55

标签: bash

字段分隔符中的数组提供了这些样式的时间码(小时:分钟:秒)。

01:00:00

正如我在下面的代码中所说:

maximum=25
count=0
countrow=1

 while [ $count -lt $maximum ]; do
    let start$countrow="${fields[$count]}"
        count=$(($count+1))
    let end$countrow="${fields[$count]}"
        count=$(($count+1))
        countrow=$(($countrow+1))
 done

应该输出为:

start1="01:00:00"
start2="02:00:00"

但是给了我这个错误:

start1=01:00:00: syntax error in expression (error token is ":00:00")

我尝试了很多方法,我猜结肠是问题但不知道如何绕过"在代码中?

1 个答案:

答案 0 :(得分:0)

It's not at all clear what you're trying to accomplish (an English-language description of the problem you're trying to solve would help), but assuming that you have something like the following:

fields=( 01:00:00 02:30:00 03:15:45 )

...you can iterate through them as follows:

for field_idx in "${!fields[@]}"; do

  # read field into hour/minute/second variables
  IFS=: read -r h m s <<<"${fields[$field_idx]}"

  # put time into start$idx one hour after the field entry
  printf -v "start$(( field_idx + 1 ))" '%02d:%02d:%02d' \
    "$(( ${h#0} + 1 ))" "$m" "$s"

done

...thus creating variables "start1", "start2" and "start3", each with a time one hour later than that given in the associated fields entry.

The ${h#0} syntax strips any leading 0, to prevent the numbers from being parsed as octal (which would make 08 and 09 invalid).