How do I write a program to produce properly quoted command line arguments for another program?

StackOverflow https://stackoverflow.com/questions/20100019

  •  03-08-2022
  •  | 
  •  

I need to write a program whose output is part of a command line for another program. e.g.

% helper
--arg1='foo bar' --arg2='another string'

which is then used as

% program `helper`

or

% program args `helper` more-args

It's simple enough without quotes, but I can't find any sort of quoting that will work.

I can get it to work like this :

% echo `helper` | xargs program

but I don't want to inflict that sort of thing on my customers.

Is there anything that 'helper' can output that will allow 'program' to be called in a simpler way than by using xargs?

有帮助吗?

解决方案

Something like this may work.

# Make helper output an array assignment
% helper
options=( --arg1='foo bar' --arg2='another string' )

# Use eval to actually define the array using the output of helper
% eval "$(helper)"
% echo "${options[0]}"
--arg1='foo bar'

# Call program using options instead of helper directly
% program "${options[@]}"

Quoting is part of the shell syntax, and you cannot have shell syntax embedded in parameters. You could also try

% eval "program $(helper)"

although I recommend against such broader use of eval. As with any use of eval, you need to be careful with what helper outputs, so that no unintended code is run.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top