Nathan Pk
Nathan Pk

Reputation: 749

storing passed arguments in separate variables -shell scripting

In my script "script.sh" , I want to store 1st and 2nd argument to some variable and then store the rest to another separate variable. What command I must use to implement this task? Note that the number of arguments that is passed to a script will vary.

When I run the command in console

./script.sh abc def ghi jkl mn o p qrs xxx   #It can have any number of arguments

In this case, I want my script to store "abc" and "def" in one variable. "ghi jkl mn o p qrs xxx" should be stored in another variable.

Upvotes: 9

Views: 25353

Answers (3)

Iluvatar
Iluvatar

Reputation: 662

Store all args in table

  vars=("$@")

  echo "${vars[10]}"

Upvotes: 2

William Pursell
William Pursell

Reputation: 212198

If you just want to concatenate the arguments:

#!/bin/sh

first_two="$1 $2"  # Store the first two arguments
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments

Note that this destroys the original positional arguments, and they cannot be reliably reconstructed. A little more work is required if that is desired:

#!/bin/sh

first_two="$1 $2"  # Store the first two arguments
a="$1"; b="$2"     # Store the first two argument separately
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments
set "$a" "$b" "$@" # Restore the positional arguments

Upvotes: 13

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Slice the $@ array.

var1=("${@:1:2}")
var2=("${@:3}")

Upvotes: 4

Related Questions