-1

I have a program that receives some options, like below:

root@machine:~$ cat notmodifiable
#!/bin/bash

echo 1: $1
echo 2: $2
echo 3: $3
echo 4: $4

And I have a script to pass a variable as argument list to this program, below script demonstrates the logic:

root@machine:~$ cat myscript
#!/bin/bash

args='a b "c 3" d'
./notmodifiable ${args}

When executing this script I got:

root@machine:~$ ./myscript
1: a
2: b
3: "c
4: 3"

What I want is:

1: a
2: b
3: c 3
4: d

I can not modify the notmodifiable script(it is actually a ELF binary), how can I achieve this by modify "myscript"?

sevenever
  • 773
  • 1
  • 8
  • 14
  • Don't do that, variables in `bash` are for scalar values. For multiple values, use an array – Inian Dec 09 '20 at 09:46
  • Does this answer your question? [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) – Lety Dec 09 '20 at 10:06

1 Answers1

1

Use arrays.

#!/bin/bash

args=(a b "c 3" d)
./notmodifiable "${args[@]}"

Quoting with [@] are they keys to passing arguments.

If you omit the quotes, e.g. ./notmodifiable ${args[@]} you will have the same issues.

If you use [*] instead of [@], e.g. ./notmodifiable "${args[*]}" you will sent a single argument concatenating the entire array.

vdavid
  • 2,434
  • 1
  • 14
  • 15
  • Thanks, How to convert a string like 'a b "c 3" d' to the array of (a b "c 3" d) ? – sevenever Dec 09 '20 at 13:18
  • If you have a fixed string at this point, you will need to choose whether you want an array ith 4 ìtems `a`, `b`, `"c 3"` and `d` or an array with 5 items `a`, `b`, `"c`, `3"` and `d`. I assume you want the former, I would just like to point out that if you reach this confusion you are kind of stuck, which usually means you should have been able to build an array beforehand. – vdavid Dec 09 '20 at 13:46
  • So if you want the former, the easy way would be to call `eval args=($args)` but this is a very bad practice because it can evaluate malicious code depending on which arguments are given – vdavid Dec 09 '20 at 13:53