Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Expanding a variable extracted from another file



TJ Luoma wrote on Sat, 16 May 2020 02:46 -0400:
> Even if I do:
> 
> echo "$MYVAR"
> 
> I get the literal "$HOME" including double-quotes in the output.
> 
> I guess this must be some foundational Unix thing that I don't
> understand properly, but all of my attempts to google it have come up
> short because I'm not sure what to search for other than "expand
> variable" but it's not quite that either.

Variable values can be any string of bytes.  If you can create
a file that contains something, you can set a variable's value to that
something.

When you type «echo "$HOME"» on the command line, HOME is the name of
a variable whose value is «/home/alice».  However, it's also possible to
have a variable whose value is literally «"$HOME"» (7 bytes).  If you
print that variable's value, you'll get those 7 bytes back verbatim:
.
    % s='"$HOME"'
    % echo $s
    "$HOME"
    % 

Values don't undergo variable expansion.  If they did, stuff like
.
    % s='"$s"'
    % echo $s
.
would either crash or hang (depending on how precisely it's implemented).

Flags such as ${(e)foo}, ${~foo}, and ${(P)foo} let you specifically ask for
a word to be expanded.  Even then, only one level of expansion happens:
.
    % s='$foo'
    % foo='$bar'
    % bar='This is bar' 
    % print -r -- ${s} 
    $foo
    % print -r -- ${(e)s} 
    $bar
    % 

Whether any of these flags is the right tool for the job depends on the context.

Cheers,

Daniel

P.S. «echo $s» does _not_ print $s verbatim for arbitrary values of $s —
for example, backslash escape sequences would be expanded — but that
doesn't matter in this case.



Messages sorted by: Reverse Date, Date, Thread, Author