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: Tue, 24 Mar 2015 22:42:25 +0000
User-agent: Mutt/1.5.21 (2010-09-15)

2015-03-24 17:13:06 -0500, Peng Yu:
> Hi,
> 
> Suppose that I have a variable with special characters, e.g, single
> quote, double quote. How to transform the variable so that it can be
> used without being quoted (for example "x'y" -> x\'y)?
> 
> One use case is something like the following. I want to construct a
> diff command on the results of calling myscript on multiple files. The
> following code works but not robustly with respect to any possible
> filenames. Does anyone know the best solution in this case?
> 
>   cmd=diff
>   for n
>   do
>     cmd="$cmd <(myscript '$n')"
>   done
>   eval "$cmd"
[...]

Best is to keep it as variables:

cmd=diff
n=1
for i do
  cmd="$cmd <(myscript -- \"\${$n}\")"
  n=$((n + 1))
done
eval "$cmd"

Then the evaluated command is:

diff <(myscript -- "${1}") <(myscript -- "${2}")...


Or you could use bash specific features like:

cmd=diff
for i do
  printf -v quoted_i %q "$i"
  cmd="$cmd <(myscript -- $quoted_i)"
done
eval "$cmd"

-- 
Stephane




reply via email to

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