help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Transform strings with special characters so that the st


From: Stephane Chazelas
Subject: Re: [Help-bash] Transform strings with special characters so that the strings don't need to be quoted?
Date: Sun, 29 Mar 2015 10:57:37 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

2015-03-25 15:42:35 -0600, Eric Blake:
[...]
> >>> shquote() {
> >>>   local q=\'
> >>>   printf "'%s'" "${1//"$q"/$q\\$q$q}"
> 
> And ${var//pattern/subst} is another bashism.

kshism as well.

[...]
> fork-free substitute:
> 
> # func_quote STRING
> # Escapes all \`"$ in STRING with another \, and stores that in $quoted
> func_quote () {
>   case $1 in
>     *[\\\`\"\$]*)
>       save_IFS=$IFS pre=.$1.
>       for char in '\' '`' '"' '$'; do
>         post= IFS=$char
>         for part in $pre; do

If you're going to use the split+glob operator, you need to
disable the glob part here.

See http://unix.stackexchange.com/q/171346 for instance.

Try:

func_quote '$*$@'

(in a non-empty directory) for instance.

>           post=${post:+$post\\$char}$part
>         done
>         pre=$post
>       done
>       IFS=$save_IFS post=${post%.}

That fails to restore IFS properly if it was originally unset.

>       quoted=${post#.} ;;
>     *) quoted=$1 ;;
>   esac
> }
> 
> func_quote "$1"
> _G_unquoted_arg=$quoted
> 
> But that thread also had a nice followup observation:
> 
> > should we test the size of the string first ?  i've written such raw shell 
> > string parsing functions before, and once you hit a certain size (like 1k+ 
> > iirc), forking out to sed is way faster, especially when running in 
> > multibyte 
> > locales (like UTF8) which most people are doing nowadays.
[...]

As I noted in my own answer to the OP, the strings don't need
quoted in this case anyway.

-- 
Stephane






reply via email to

[Prev in Thread] Current Thread [Next in Thread]