Preserving quotes in bash function parameters

后端 未结 8 665
天涯浪人
天涯浪人 2020-12-05 05:13

What I\'d like to do is take, as an input to a function, a line that may include quotes (single or double) and echo that line exactly as it was provided to the function. For

相关标签:
8条回答
  • 2020-12-05 05:36

    The reason this happens is because bash interprets the arguments, as you thought. The quotes simply aren't there any more when it calls the function, so this isn't possible. It worked in DOS because programs could interpret the command line themselves, not that it helps you!

    0 讨论(0)
  • 2020-12-05 05:36

    This:

    ponerApostrofes1 () 
    {
        for (( i=1; i<=$#; i++ ));
        do
            eval VAR="\${$i}"; 
            echo \'"${VAR}"\';
        done; 
        return; 
    }
    

    As an example has problems when the parameters have apostrophes.

    This function:

    ponerApostrofes2 () 
    { 
        for ((i=1; i<=$#; i++ ))
        do
            eval PARAM="\${$i}";
            echo -n \'${PARAM//\'/\'\\\'\'}\'' ';
        done;
        return
    }
    

    solves the mentioned problem and you can use parameters including apostrophes inside, like "Porky's", and returns, apparently(?), the same string of parameters when each parameter is quoted; if not, it quotes it. Surprisingly, I don't understand why, if you use it recursively, it doesn't return the same list but each parameter is quoted again. But if you do echo of each one you recover the original parameter.

    Example:

    $ ponerApostrofes2 'aa aaa' 'bbbb b' 'c' 
    'aa aaa' 'bbbb b' 'c'
    
    $ ponerApostrofes2 $(ponerApostrofes2 'aa aaa' 'bbbb b' 'c' )
    ''\''aa' 'aaa'\''' ''\''bbbb' 'b'\''' ''\''c'\''' 
    

    And:

    $ echo ''\''bbbb' 'b'\'''
    'bbbb b'
    $ echo ''\''aa' 'aaa'\'''
    'aa aaa'
    $ echo ''\''c'\''' 
    'c'
    

    And this one:

    ponerApostrofes3 () 
    { 
        for ((i=1; i<=$#; i++ ))
        do
            eval PARAM="\${$i}";
            echo -n ${PARAM//\'/\'\\\'\'} ' ';
        done;
        return
    }
    

    returning one level of quotation less, doesn't work either, neither alternating both recursively.

    0 讨论(0)
提交回复
热议问题