Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Bash script arguments $@ in a variable

How can I store $@ in a variable while keeping its properties?

I want to obtain exactly the same behavior even if I use $@ or my own variable in all possible situations.

The attempts below didn't work:

args=$@
args2="$@"        # the arguments are combined (see the last output paragraph)

I tested them using the following line:

s.sh A B="       " C

s.sh

#!/bin/bash

args=$@
args2="$@"
#args3 = ? - TODO

echo $args
echo $args2
echo $@
#echo $args3   

echo

echo "$args"
echo "$args2"
echo "$@"
#echo "$args3"

echo

java A $args
java A $args2
java A $@
#java A $args3

echo

java A "$args"
java A "$args2"
java A "$@"
#java A "$args3"

A.java

import java.util.Arrays;

public class A {
    public static void main(String args[]){
        System.out.println(args.length + ": " + Arrays.asList(args));
    }
}

Actual output:

A B= C
A B= C
A B= C

A B= C
A B=        C
A B=        C

3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]

1: [A B= C]
1: [A B=        C]
3: [A, B=       , C]

Expected output (if TODO is replaced by a solution) and echos are enabled

A B= C
A B= C
A B= C
A B= C

A B= C
A B=        C
A B=        C
A B=        C

3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]

1: [A B= C]
1: [A B=        C]
3: [A, B=       , C]
3: [A, B=       , C]
like image 843
ROMANIA_engineer Avatar asked Dec 25 '22 19:12

ROMANIA_engineer


2 Answers

You can store it in an array:

args=("$@")

then you can access each of the arguments with index: "${args[index]}" and all arguments at once with "${args[@]}".

like image 51
Jahid Avatar answered Jan 04 '23 22:01

Jahid


It depends what you want to do. Using $@ keeps the command-line arguments separated, if you want to join them together as a single string then use $* instead. For example:

args="$*"
java A $args

When "$*" is used then the command-line arguments are joined into one string using the first character of IFS as the "glue" between each argument. By default that is a space. The only issue with this is if any of the arguments themselves contain whitespace. If you know that spaces are going to be used, not tabs, then you can mess with IFS:

oldIFS="$IFS"
IFS=$'\t'
args="$*"
java A.py $args

IFS="$oldIFS"

Edit: since you wish to keep them separate, then use an array:

args=("$@")
java A "${args[@]}"

Using an "index" of @ has a similar effect to "$@" (you can also use * to join elements together, just like "$*").

like image 20
cdarke Avatar answered Jan 04 '23 22:01

cdarke