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

Re: Please help me quote ! :)

On Mon, 26 Feb 2018 18:50:38 +0100
tuxic@xxxxxxxxx wrote:
> is there a way to automatically escape all "bad" characters
> (like spaces) while expanding a shell variable containing a
> "bad" filename?

I assume the intention is so that anything that would be special
to the shell is hidden away from immediate expansion, but in such a away
that when you output the result later you get back the original file name.

It's easy using the (q) family of parameter flags.  So, for example,

% touch 'space file'
% files=(*)
% print -r $files
space file
% print -r ${(q)files}
space\ file

I presume that output (the -r stops print from swallowing the backslash)
is the sort of thing you're after.  (q) is smart about what needs
quoting.  (qq), (qqq), (qqqq), (q-) and (q+) are only cosmetically
different: they have the same practical effect unless you want the input
to be evaluated by a different shell.

The quoting is by word, so if there were more matches in $files, all the
file names get that behaviour separately (they aren't joined by
quoted spaces).

However, with native zsh options, you only need this if you're going to
use the variable in some context where the value is going to be expanded
again, like an "eval."  Otherwise, the fact that zsh leaves the contents
of variables well alone if there substituted back onto the command line,
unlike other shells where you need double quotes,  means that just using
the variable itself --- $files here --- will work most of the time.

So if thisn't quite what you want, you'll need to tell us what you're
actually doing (usually a good plan anyway).


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