简体   繁体   中英

Parse an array in KSH shell?

i'm a newbie to shell coding. My intention is to accept arguments from the command line, in CSV format, parse the input into an array. Something like,

sh scriptname.sh 123,345,456,789...

123,345,456..should be stored into an array. So far, i have acheived the following,

#!/bin/ksh
#get the argument to be parsed
RID=$1
#Parse the argument, remove the space and store into and variable
str=`echo $RID | sed 's/,/\ /g'
#Assign the value to a variable
set  -A RIDS $str
#Get the count of arguments in the array
num=${#RIDS[@]}
echo $num
#Display the elements in the array
i=0
while [ $num -gt 0 ] do
echo ${A_RIDS[i]}
i=`expr $1 + 1`
num=`expr $num - 1`
done

But it throws an error as "Bad substitution" (at line7)

Alternatively I have tried in the following way (doing it in a single shot)like the below

set -A A_RID $(echo $RID | sed 's/,/\ /g')

instead of

str=`echo $RID | sed 's/,/\ /g'
set  -A RIDS $str

This time it shows "unexpected token '(' on the line of

set -A A_RID $(echo $RID | sed 's/,/\ /g').

Can you tell where i'm doing it wrong? Thanks in advance!

Hmm, works for me. What version of ksh do you have?

$ ksh
$ RID=123,345,456,789
$ set -A A_RID $(echo $RID | sed 's/,/\ /g')
$ printf "%s\n" "${A_RID[@]}"
123
345
456
789
$ ksh --version
  version         sh (AT&T Research) 93u+ 2012-08-01

Depending on your ksh version, it can be as short as

IFS=, read -A A_RID <<< "$RID"

By starting your script by

sh scriptname.sh 123,345,456,789...

you let sh execute it, not ksh . Set execute permission on scriptname.sh and type just

scriptname.sh 123,345,456,789...

to have it executed by /bin/ksh . Then you can apply yourself to errors not coming from using the wrong shell.

Besides, you should revert your edit of your question where you removed a needed backtick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM