Dave
Dave

Reputation: 19090

In bash, how do I set a variable to encompass a variable number of command line arguments?

I’m using bash shell. I’m writing a script and I would like to capture a variable number of arguments passed to my script after and including argument #5. So far I have this …

#!/bin/bash
…
declare -a attachments
attachments=( "$5" )

But what I can’t figure out is how to write the “attachments” line to encompass argument #5 and any arguments that follow that. So in the following example

sh my_script.sh arg1 arg2 arg3 arg4 “my_file1.csv” “my_file2.csv”

I would want attachments to consist of “my_file1.csv” and “my_file2.csv,” whereas in this example …

sh my_script.sh arg1 arg2 arg3 arg4 “my_file1.csv” “my_file2.csv” “my_file3.csv”

I would want attachments to contain “my_file1.csv,” “my_file2.csv,” and “my_file3.csv.”

Upvotes: 2

Views: 63

Answers (2)

pjh
pjh

Reputation: 8064

srcdir=$1
destdir=$2
optflag=$3
barflag=$4
attachments=( "${@:5}" )

Upvotes: 2

Toby Speight
Toby Speight

Reputation: 30706

The usual idiom is to capture the fixed arguments into variables, and then the remainder are available as "$@":

srcdir="$1"; shift
destdir="$1"; shift
optflag="$1"; shift
barflag="$1"; shift

(cd "$destdir" && mv -t "$destdir" "-$optflag" "$@" )

This idiom easily extends should you find the need for a variable number of arguments preceding the list:

while [ "${1#-}" != "$1" ]
do
    case "$1" in
      -foo) foo="$2";shift 2 ;;
      -bar) bar="$2";shift 2 ;;
      -baz) bar=true;shift 1 ;;
      --) shift; break;
    esac
done
# rest of arguments are in "$@"

Upvotes: 1

Related Questions