sagar verma
sagar verma

Reputation: 432

pass n number of argument to bash script

I wanted to pass 2 fixed and remaining 'n' number of arguments to the script which I wanted to store in an array variable. Could someone please suggest how to achieve this via code. Example:

sh myScript.sh fixedArgument1 fixedArgument2 var1 var2 ... varN

N can be anything but not more than 15.

Also, I can get the value of fixedArgument1 in script via $1 and fixedArgument2 $2 but how to put the remaining arguments in array variable.

Upvotes: 2

Views: 1137

Answers (2)

William Pursell
William Pursell

Reputation: 212198

Just shift off the fixed position arguments and get the remainder with "$@". eg:

#!/bin/bash

echo first arg: "$1"
echo 2nd arg: "$2"
shift
shift
array=("$@")
for element in "${array[@]}"; do
    echo "$element"
done

Make sure you're using a shell that supports arrays. sh may not, as /bin/sh is often not bash.

But note that it sounds like you are probably working too hard. Why bother putting the arguments in an array at all? You can access them via $@ just as easily as you will access them from the array, and it probably makes more sense to do that. The array is probably just going to obfuscate the code. For example:

#!/bin/sh

echo "first arg: '$1'"
echo "2nd arg: '$2'"
shift 2  # discard the first two arguments
if test $# -gt 0; then
    echo There are $# arguments remaining:
    i=1
    # Iterate over the remaining arguments
    for x; do echo "arg $((i++)): '$x'"; done
fi

Upvotes: 3

konsolebox
konsolebox

Reputation: 75458

#!/bin/bash

function main {
    local arg1=$1 arg2=$2 remaining=("${@:3}")
    ...
}

main "$@"

Also as suggested already, you don't need to store remaining arguments to an array, and you can access it directly either through "${@:3}", or through "$@" after executing shift 2. In a for loop the in ... part can be ignored if target is "$@" and positional parameters aren't modified inside the loop through set -- since this may or may not affect the loop arguments depending on implementation.

Upvotes: 2

Related Questions