无法在shell脚本中向数组元素添加整数

时间:2012-11-10 11:58:30

标签: arrays bash shell

我试图在svn信息上解析输出,而不依赖于像sed或awk这样的外部shell命令。这纯粹是学术性的,因为我知道我可以用这些工具进行心跳。

我解析的输出是:

Path: .
URL: svn://brantwinter@192.168.10.222/handbrake_batch/trunk/handbrake
Repository Root: svn://ilium007@192.168.10.222/handbrake_batch
Repository UUID: 99c2cca7-102b-e211-ab20-02060a000c0b
Revision: 6
Node Kind: directory
Schedule: normal
Last Changed Author: ilium007
Last Changed Rev: 6
Last Changed Date: 2012-11-10 19:00:35 +1000 (Sat, 10 Nov 2012)

这是我的代码:

#!/bin/bash

#set -x

OLD_IFS="$IFS"
IFS=$'\r\n'

# Get the output from svn info into an array
SVN_INFO_ARR=(`svn info`)
COUNT=0
for i in ${SVN_INFO_ARR[@]}; do
    echo $COUNT
    echo "$i"
    (( COUNT++ ))
done

# Get the element that says "Revision: 6"
REV_ARR=${SVN_INFO_ARR[4]}

# Testing the loop over what should be a two element array
COUNT=0
for i in ${REV_ARR[@]}; do
    echo $COUNT
    echo "$i"
    (( COUNT++ ))
done

#This should give the number 6 (or string or something)
REV_NUMBER=${REV_ARR[1]}

echo ${REV_NUMBER}

### INCREMENT REVISION NUMBER FROM ARRAY ELEMENT ###

#NEW_REV_NUMBER= ????? + 1

IFS="$OLD_IFS"

我希望能够接受字符串:

修订版:6

并拉出6并递增1,这样我就可以更新发布的txt文件,使其包含在SVN提交中。

我已经尝试将6转变成7小时一小时,感觉自己像个白痴,因为我无法做到。

4 个答案:

答案 0 :(得分:3)

你需要括号:改变这个:

# Get the element that says "Revision: 6"
REV_ARR=${SVN_INFO_ARR[4]}

到此:

# Get the element that says "Revision: 6"
REV_ARR=(${SVN_INFO_ARR[4]})

#This should give the number 6 (or string or something)
REV_NUMBER=${REV_ARR[1]}

所以你将能够:

((REV_NUMBER++))

修改

正如你所写:

SVN_INFO_ARR=(`svn info`)

而不只是:

SVN_INFO_ARR=`svn info`

在bash中使用括号来定义数组。看看:

man -Len -P'less +"/^ *Arrays"' bash

答案 1 :(得分:3)

不是硬编码数组索引,更好的方法是过滤掉你需要的行并提取数字

这是使用正则表达式(Bash 4)

的一种方式
while read -r line; do
    if [[ $line =~ Revision:\ ([0-9]+) ]]; then
         new_rev_num=$((BASH_REMATCH[1]+1))
         echo $new_rev_num
         break
    fi
done < $(svn info)

答案 2 :(得分:0)

使用grep仅选择您需要的行。然后,使用参数扩展删除“Revision:”。最后,使用let进行算术运算:

REVISION=$(svn info | grep '^Revision:')
REVISION=${REVISION#* }
let REVISION++

答案 3 :(得分:0)

此代码最终有效:

#!/bin/bash

set -x

OLD_IFS="$IFS"
IFS=$'\r\n'

# Get the output from svn info into an array
SVN_INFO_ARR=(`svn info`)

IFS="$OLD_IFS"

# Get the element that says "Revision: 6"
REV_ARR=(${SVN_INFO_ARR[4]})

#This should give the number 6 (or string or something)
REV_NUMBER=${REV_ARR[1]}
echo $REV_NUMBER
echo $(( REV_NUMBER + 1 ))

上面的答案让我感到难过,因为它错过了前面的$:

echo $(( REV_NUMBER + 1 ))

并且((REV_NUMBER++))符号不起作用,我仍然有6,而不是7:

+ OLD_IFS='     
'
+ IFS='
'
+ SVN_INFO_ARR=(`svn info`)
++ svn info
+ IFS='     
'
+ REV_ARR=(${SVN_INFO_ARR[4]})
+ REV_NUMBER=6
+ echo 6
6
+ echo 6
6