Kedar Joshi
Kedar Joshi

Reputation: 1462

How to store command line arguments for future use?

I have a big bash script (version 3.2.51(1)-release) and I need to store command line arguments for use in the script.

I checked many threads here and people suggested to use "$@" to access all arguments.

If I run this script (test.sh) -

#!/bin/bash
echo "$@";

$> ./test.sh 1 2 3
1 2 3

But if i run this

#!/bin/bash
set args1 = "$@";

... do some work here ...

echo $args1;

I get no output when run. What am I missing here? I want to store the arguments without modifying them and then use them sometime later in the script.

Upvotes: 5

Views: 4708

Answers (2)

Jahid
Jahid

Reputation: 22428

Use

args1="$*"

instead of set args1 = "$@"; if you want all arguments as a single string.

Note: Try to use your variables double quoted, otherwise you will loose white spaces.

Or if you want to treat each one of them differently then you need an array:

argarr=("$@")

Then you can access each element of the array with "${argarr[$index]}" and all element at once with "${argarr[@]}"

Upvotes: 4

anubhava
anubhava

Reputation: 785128

Store all the arguments in an array:

args=("$@")

Then print them as:

printf "%s\n" "${args[@]}"

Upvotes: 10

Related Questions