abcdef
abcdef

Reputation: 137

How to read values from command line in bash script as given?

I want to pass arguments to a script in the form

    ./myscript.sh -r [1,4] -p [10,20,30]

where in myscript.sh if I do:

    echo $@

But I'm getting the output as

   -r 1 4 -p 1 2 3

How do I get output in the form of

   -r [1,4] -p [10,20,30]

I'm using Ubuntu 12.04 and bash version 4.2.37

Upvotes: 0

Views: 340

Answers (3)

glenn jackman
glenn jackman

Reputation: 247210

You can turn off filename expansion

set -f
./myscript.sh -r [1,4] -p [10,20,30]

Don't expect other users to want to do this, if you share your script.

The best answer is anishane's: just quote the arguments

./myscript.sh -r "[1,4]" -p "[10,20,30]"

Upvotes: 0

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4051

You can just the escape the brackets[]. Like this,

./verify.sh  -r \[1,4\] -p \[10,20,30\]

You can print this using the echo "$@"

Upvotes: 0

anishsane
anishsane

Reputation: 20980

You have files named 1 2 3 & 4 in your working directory.

Use more quotes.

./myscript.sh -r "[1,4]" -p "[10,20,30]"

[1,4] gets expanded by bash to filenames named 1 or , or 4 (whichever are actually present on your system).
Similarly, [10,20,30] gets expanded to filenames named 1 or 0 or , or 2 or 3.

On similar note, you should also change echo $@ to echo "$@"

On another note, if you really want to distinguish between the arguments, use printf '%s\n' "$@" instead of just echo "$@".

Upvotes: 4

Related Questions