[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Use `find' "-printf" predicate inside bash script
From: |
JB |
Subject: |
Re: Use `find' "-printf" predicate inside bash script |
Date: |
Tue, 19 Oct 2021 19:36:19 +0000 |
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
> Date: Mon, 18 Oct 2021 16:39:12 -0400
> From: Eli Schwartz eschwartz@archlinux.org
> To: help-bash@gnu.org
> Subject: Re: Use `find' "-printf" predicate inside bash script
>
> On 10/18/21 4:24 PM, JB wrote:
>
> > This `find' command works on the command line:
> >
> > find /tmp/ -type f -mtime -1 -delete -printf "deleted file: %f\\n"
> >
> > But it doesn't work inside this script:
> >
> > #!/bin/bash
> > args_find='-type f -mtime -1 -delete -printf "deleted file: %f\\n"'
> > find /tmp/ $args_find
>
> So... it doesn't work when you do something completely different that
> you didn't do on the command line, then?
>
> $ set -x
>
> $ find . $args_find
>
> - find . -type f -mtime -1 -delete -printf '"deleted' file: '%f\n"'
>
> Note how the " chars are treated as text, not as bash quotes.
Testing it first on the command line proved the syntax was correct for `find'.
That's the point. I already noticed what Bash was doing to the quotes when I
debugged the script using "-x" on the shebang line, which is why I attempted to
escape them without success.
> > It only works when written like this:
> >
> > #!/bin/bash
> > args_find="-type f -mtime -1 -delete -printf"
> > args_print="deleted file: %f\\n"
> > find /tmp/ $args_find "$args_print"
> >
> > I've tried using arrays with both "@" and "*", but same result.
> > I tried escaping the double-quotes, but `find' complains: warning:
> > unrecognized escape` \"'
> > paths must precede expression: `file'
> >
> > What's the proper way to do this inside a variable which doesn't trip up
> > "-printf"?
>
> It looks like you expected $args_find to be treated as content which is
> run through "eval". Incidentally, please do NOT use eval.
>
> Instead, use arrays:
>
> args_find=(-type f -mtime -1 -delete -printf "deleted file: %f\n")
>
> find /tmp/ "${args_find[@]}"
Yes, that was the key: double-quoting args_find when expanding on the final
line.