Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store command line arguments for future use?

Tags:

bash

shell

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.

like image 238
Kedar Joshi Avatar asked Dec 19 '22 03:12

Kedar Joshi


2 Answers

Store all the arguments in an array:

args=("$@")

Then print them as:

printf "%s\n" "${args[@]}"
like image 132
anubhava Avatar answered Jan 02 '23 08:01

anubhava


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[@]}"

like image 34
Jahid Avatar answered Jan 02 '23 08:01

Jahid