How can bash
use a variable for the format of find
's -printf
statement? I am trying to convert the following:
find ./ -type f -printf "File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n"
which prints the following:
File: ./file_20180926_220000.txt has modification time [2018-09-26 22:00:00.0000000000 CDT]
File: ./file_20180926_210000.txt has modification time [2018-09-26 21:00:00.0000000000 CDT]
File: ./file_20180926_230000.txt has modification time [2018-09-26 23:00:00.0000000000 CDT]
I want the printf statement to be held in a variable instead, like the following illustrates (but fails).
operation="-printf \"File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n\""
find ./ -type f $operation
The output of that is:
find: paths must precede expression: %p
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
Simpler printf formats work, like if I just use operation="-printf %p"
, but as soon as I use spaces in the format, I get the error above. I also tried to escape the spaces with \
, but I haven't been able to get it to work.
I would like to avoid eval
if possible, unless someone can suggest how to use it safely in this context.
Note: The following works, but requires two variables, while I would prefer to keep just one:
operation="-printf"
format="File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n"
find ./ -type f $operation "$format"
File: ./file_20180926_220000.txt has modification time [2018-09-26 22:00:00.0000000000 CDT]
File: ./file_20180926_210000.txt has modification time [2018-09-26 21:00:00.0000000000 CDT]
File: ./file_20180926_230000.txt has modification time [2018-09-26 23:00:00.0000000000 CDT]