开发者

How to preserve single and double quotes in shell script arguments WITHOUT the ability to control how they pass

I need to receive arguments I have no control over into a shell script, and preserve any single or double quotes. For instance, a script that simply outputs the given arguments should act as follows:

> my_script.sh "double" 'single' none
"double" 'single' none

I don't have the privilege of augmenting the arguments such as in:

> my_script.sh \"double\" \'single\' none

or

> my_script.sh '"double"' "'single'" none

And neither "$@" nor "$*" work. I also thought of reading from STDIN and try something like:

> echo "double" 'single' none | my_script.sh

thinking it may help, but no breakthrough开发者_如何学C so far.

Any suggestions?

CSH / PERL solutions are welcomed.


This is not possible (without escaping), because the shell processes the arguments and removes the quotes before your script is called. As a result, your script does not know about the quotes specified on the command line.


You cannot recover the single/double quotes exactly as they were, because the shell 'eats' them. If you need to call some other script from your script, you can e.g. single quote the arguments again. Here is a PERL solution I use:

sub args2shell
{
    local (@argv) = @_;
    local $" = '\' \'';
    local (@margv);

    @margv = map { s/'/'\\''/g; $_ } @argv;
    return "\'@margv\'" if @margv;
    return undef;   
} 

Example usage:

$args = args2shell @ARGV;
open F, "find -follow $args ! -type d |"; 
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜