help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] bash variable interpolation


From: John Kearney
Subject: Re: [Help-bash] bash variable interpolation
Date: Fri, 20 Mar 2015 06:02:28 +0100

Here is a simple example of how to do this manually.

  ks_IntrStr_ExpandVars(){
    local CLine Key
    while IFS= read -r CLine ; do
      while Key=${CLine##*\$\{} && [ "${Key}" != "${CLine}" ] ; do
        Key=${Key%%\}*}
        if [ -v "${Key}" ]; then
          KeyValue=${!Key}
        else
          KeyValue="<unset-${Key}>"
        fi
        CLine=${CLine//\$\{${Key}\}/${KeyValue}}
      done
      echo "${CLine}"
    done <<EOF
${1:-}
EOF
  }

  TestFormat='
Hello ${a} ${b} Hello
Hello ${${a}} Hello
'
  ks_IntrStr_ExpandVars "${TestFormat}"
  a=TestVarA ks_IntrStr_ExpandVars "${TestFormat}"
  a=TestVarA b=TestVarB ks_IntrStr_ExpandVars "${TestFormat}"
  TestVarA=TestTestVarA a=TestVarA b=TestVarB ks_IntrStr_ExpandVars
"${TestFormat}"

Note it does recursive expansion.
so the output of the above would be.


Hello <unset-a> <unset-b> Hello
Hello <unset-<unset-a>> Hello


Hello TestVarA <unset-b> Hello
Hello <unset-TestVarA> Hello


Hello TestVarA TestVarB Hello
Hello <unset-TestVarA> Hello


Hello TestVarA TestVarB Hello
Hello TestTestVarA Hello





On Fri, Mar 20, 2015 at 4:53 AM, Ken Irving <address@hidden> wrote:

> On Thu, Mar 19, 2015 at 08:03:01PM -0400, Dave Rutherford wrote:
> > On Thu, Mar 19, 2015 at 7:37 PM, Peng Yu <address@hidden> wrote:
> > > On Thu, Mar 19, 2015 at 5:42 PM, Eric Blake <address@hidden> wrote:
> > >> On 03/19/2015 04:04 PM, Peng Yu wrote:
> > >>> I want to interpolate variable in a bash string variable. But the
> > >>> following code shows the spaces are not maintained.
> > >>
> > >> Insufficient quoting on your part.
> > >>
> > >>> There is some
> > >>> built-in features in perl to do string interpolation. Does anyone
> know
> > >>> the best way to do string interpolation in bash? Thanks.
> >
> > I feel dumb. What is meant by `string interpolation'?
>
> I think I first saw that term used in Perl, meaning to expand (perl)
> variables in place in a string, but I didn't remember it or recognize
> it in this context until a few posts in.
>
> > > The real problem is that I want to replace some bash variables in a
> > > file and then print the output.
>
> A common term for expanding variables or tokens in a file is 'template
> expansion'.  I shy away from eval, so would probably treat the variables
> as string tokens and subsitute the values in a loop.
>
> Ken
>
>


reply via email to

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