[英]bash array variable echo error
I have been trying to figure this out for hours and it just keeps giving me problems. 我已经尝试了好几个小时才能解决这个问题,但它一直给我带来麻烦。 I'm trying to pass 2 delimiter-containing strings as paramters to a bash script, iterate through them and echo the corresponding value 1,2,3 etc from array 1 in array 2's iteration 我正在尝试将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
however, running 但是,跑步
./script.sh file1@@file2@@file3@@file4 thumb1@@thumb2@@thumb3@@thumb4
it just gives me this output 它只是给我这个输出
./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
the output i need is 我需要的输出是
file1
file2
file3
file4
IFS
supports only single character delimiter. IFS
仅支持单个字符定界符。 You also should use /bin/bash
in shebang instead of /bin/sh
. 您还应该在shebang中使用/bin/bash
而不是/bin/sh
。
You script can be like this: 您的脚本可以像这样:
#!/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
Output: 输出:
file1
file2
file3
file4
You are specifiing sh as the shell for the script. 您将sh指定为脚本的外壳。 That (quite old) shell does not support arrays, thus all var[index] will fail. 该(相当古老的)shell不支持数组,因此所有var [index]都会失败。 If you could use bash, then this simpler script should work for you: 如果可以使用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
call it as this: 这样称呼它:
./script "file1 file2 file3 file4" "thumb1 thumb2 thumb3 thumb4"
The double quotes will keep the input as one parameter until an un-quoted $1 is used inside the script. 双引号会将输入作为一个参数,直到脚本内部使用未加引号的$ 1为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.