Preserving quotes in bash function parameters

后端 未结 8 810
天涯浪人
天涯浪人 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

    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.

提交回复
热议问题