0

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

9
  • 1
    I'm getting output like as you need: Please add info about you OS and bash version cmd: ./test1.bash -r [1,4] -p [10,20,30] output: -r [1,4] -p [10,20,30] Commented Mar 12, 2015 at 7:08
  • I ran it using zsh, csh, sh and bash interpreter and they all returned your desired output... Commented Mar 12, 2015 at 7:13
  • bash version is irrelevant in this particular case. Commented Mar 12, 2015 at 7:13
  • Those aren't bash versions... But I get your point :) Commented Mar 12, 2015 at 7:15
  • Looks like [] are interptereted as {}. Is it possible that this behaviour is defined somewhere? What do you get if you try [1..10] ? Commented Mar 12, 2015 at 7:15

3 Answers 3

4

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 "$@".

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, brilliant. I would have searched for a while before figuring that out!
printf '%s\n' "$@" is still giving me the same output. So does echo "$@". I want the arguments to be read as is without adding any more quotes.
@abcdef, then you need to remove those files so that the shell patterns ([1,4] and [10,20,30]) no longer match them. The safe way is to use more quotes when you call your script.
"I want the arguments to be read as is without adding any more quotes": [1,4] will get expanded to 1 4 as read by script. "[1,4]" will be read as [1,4] by the script. "\"[1,4]\"" will get read as "[1,4]". Second option is what you need.
0

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]"

Comments

0

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 "$@"

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.