bash数组变量回显错误

时间:2015-10-26 06:37:48

标签: arrays bash variables

我一直试图解决这个问题几个小时,它一直在给我带来麻烦。我试图将包含2个分隔符的字符串作为参数传递给bash脚本,迭代它们并在数组2的迭代中从数组1中回显相应的值1,2,3等

#!/bin/sh

export IFS='@@'
ThumbFilenames=$1

counterFiles=1

for thumbFilename in $ThumbFilenames; do
        thumbFile[${counterFiles}]="${thumbFilename}"
        counterFiles=$((counterFiles+1))
done

ThumbsIn=$2
counterThumbs=1
for thumbnumber in $ThumbsIn; do
        echo "${thumbFile[${counterThumbs}]}"
        echo "\n"
        counterThumbs=$((counterThumbs+1))
done

然而,正在运行

./script.sh file1@@file2@@file3@@file4 thumb1@@thumb2@@thumb3@@thumb4

它只是给了我这个输出

./script.sh: 9: thumbFile[1]=file1: not found
./script.sh: 9: thumbFile[2]=: not found
./script.sh: 9: thumbFile[3]=file2: not found
./script.sh: 9: thumbFile[4]=: not found
./script.sh: 9: thumbFile[5]=file3: not found
./script.sh: 9: thumbFile[6]=: not found
./script.sh: 9: thumbFile[7]=file4: not found

我需要的输出是

file1
file2
file3
file4

2 个答案:

答案 0 :(得分:1)

IFS仅支持单字符分隔符。您还应该在shebang中使用/bin/bash而不是/bin/sh

你的脚本可以是这样的:

#!/usr/bin/env bash

export IFS='@'
ThumbFilenames="${1//@@/@}"

thumbFile=()

for thumbFilename in $ThumbFilenames; do
   thumbFile+=("$thumbFilename")
done

ThumbsIn="${2//@@/@}"
counterThumbs=0
for thumbnumber in $ThumbsIn; do
   echo "${thumbFile[${counterThumbs}]}"
   ((counterThumbs++))
done

<强>输出:

file1
file2
file3
file4

答案 1 :(得分:0)

您将sh指定为脚本的shell。那个(相当古老的)shell不支持数组,因此所有var [index]都会失败。如果你可以使用bash,那么这个更简单的脚本应该适合你:

#!/bin/bash

thumbFile=(x $1)  # This simple line will break $1 into an array
                  # with the index tumbFile[1] equal to file1.

unset thumbFile[0]   # Cosmetic: Remove the array element that contains x.

printf "%s " "${thumbFile[@]}"; echo; echo  # print all values in thumbFile

ThumbsIn=$2
counterThumbs=1
for thumbnumber in $ThumbsIn; do
        echo "${thumbFile[${counterThumbs}]}"
        echo -e "\n"
        counterThumbs=$((counterThumbs+1))
done

称之为:

./script "file1 file2 file3 file4" "thumb1 thumb2 thumb3 thumb4"

双引号将输入作为一个参数,直到脚本中使用未引用的$ 1.