pri
pri

Reputation: 119

How to read command line argument in shell sript

I need to read command line argument which is passing as scriptname –c "30,31,32,33,34,35"

and convert it to

myArray=( 30 31 32 )

Upvotes: 0

Views: 85

Answers (2)

cdarke
cdarke

Reputation: 44354

Try the following:

while getopts c: option
do
    case $option in
       c) data="$OPTARG"
          ;;
    esac
done

oldIFS="$IFS"
IFS=','
myArray=($data)
IFS="$oldIFS"

echo ${myArray[@]}

The c: after getoptsindicates that we have an option -c, the : indicates it is followed by an argument, which is retrieved using $OPTARG.

IFS if the Inter Field Separator which I reset to a comma in order to create the array.

Upvotes: 1

sharathkj
sharathkj

Reputation: 11

You can use getopts command to read the arguments. Please refer the link for the usage example of how to use getopts in bash

Once you have the variables, you can easily create an array This link might be useful. Arrays in unix shell?

Upvotes: 1

Related Questions