简体   繁体   中英

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.

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="$*"

No loop or shift ing 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

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