XYZ_Linux
XYZ_Linux

Reputation: 3597

Saving the arguments in different variables passed to a shell script

I need to save two command line arguments in two different variables and rest all in third variable. I am using following code

while [ $# -ge 2 ] ; do
  DirFrom=$1
  Old_Ver=`basename $1`
  shift
  DirTo=$1
  shift
  pdct_code=$@
  shift
done

This code is failing if I send more than three arguments . Please suggest how can I save 3rd 4th and so on variable in pdct_code variable.

Upvotes: 0

Views: 87

Answers (2)

chepner
chepner

Reputation: 530922

No loop or shifting is needed. Note that pdct_code may need to be an array, to preserve the exact arguments passed to your script.

if [ $# -ge 2 ]; then
    DirFrom=$1
    Old_Ver=$(basename "$1")
    DirTo=$2
    pdct_code="${@:3}"
    # pdct_code=( "${@:3}" )
done

Upvotes: 0

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

You're not entering the loop when you have more than two arguments. You can bump the argument limit like so:

while [ $# -ge 3 ]; do
    :
done

or better yet just parse your arguments without looping at all. For example:

DirFrom="$1"
Old_Ver=`basename "$1"`
DirTo="$2"
pdct_code="$*"

Upvotes: 2

Related Questions