9

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.

3 Answers 3

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

Note that this will only work if the arguments don't contain any spaces.
@HelloGoodbye This works just fine if the arguments contain whitespace. You cannot reliably reproduce the argument from the value of "remainder" in that case, but $a, $b and the new positional arguments are correct.
Yes, you're right, I don't know what I was thinking. I probably reacted the fact that the distinction between the first and second arguments is lost in your first code snipped if any of them contains spaces. But maybe that's okay for the OP.
4

Slice the $@ array.

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

1 Comment

Note that since these are stored as arrays (which is the right way to do it), they must be expanded with a special syntax: echo "first two=" "${var1[@]}"; echo "remainder=" "${var2[@]}"
3

Store all args in table

  vars=("$@")

  echo "${vars[10]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.