augurar
augurar

Reputation: 13016

One-liner to quote string in bash

Consider the following bash function:

function quote { 
    declare quoted=${1//\'/\'\\\'\'}
    echo "'$quoted'"
}

This function wraps the argument in single quotes, and replaces each existing single quote with the string '\'':

$ quote "a'b"
'a'\''b'

It seems like the function body could be written in one line:

function my_quote {
    echo "'${1//\'/\'\\\'\'}'"
}

However, this doesn't work for some reason:

$ my_quote "a'b"
'a\'\\'\'b'

So, my questions are (1) Why doesn't the one-line version work?, and (2) Is there some way to make it work by, say, adding some more backslashes?

By the way, if you're curious, this snippet demonstrates why such a function is useful:

foo="some string generated at runtime, possibly containing special characters"
cmd="somecommand $(quote "$foo")"
ssh user@host "$cmd"

Upvotes: 2

Views: 230

Answers (1)

konsolebox
konsolebox

Reputation: 75488

(1) It's probably how bash differently handles the parameter expansion inside "" than the one in assignments. I see it actually as a bug since the quoted string is not properly unquoted. It works properly somehow if you use other variables inside i.e.

"${var//x/$other}"

(2) This is not a one-line way, just another way. You could place the variables on other places but it's still not one line in my opinion.

function my_quote {
    local r="'\''"
    echo "'${1//\'/$r}'"
}

You could also place an echo under a subshell $() but that's still two lines or two commands in one.

Upvotes: 1

Related Questions