Ariel
Ariel

Reputation: 139

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 so far.

Any suggestions?

CSH / PERL solutions are welcomed.

Upvotes: 0

Views: 2761

Answers (2)

Tomas
Tomas

Reputation: 59465

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 |"; 
...

Upvotes: 0

dogbane
dogbane

Reputation: 274582

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.

Upvotes: 3

Related Questions