I need to use "find" command to find several different sets of files in my Bash function, depending on my script input.
So, I have thing like:
DAYS=30
case $1 in
A1) ARGLINE="-name 'FOO*.xml' -or -name 'BAR*.xml' -or -name 'BTT*.txt'"
;;
A2) ARGLINE="-name 'PO*xml' -or -name 'PR*xml'"
;;
...
esac
find . -maxdepth 1 -type f -mtime +${DAYS} `${ARGLINE}`
This works.
However, as soon as I want to use variable for number of days to search back to, like this:
DAYS=30
case $1 in
A1) ARGLINE="-name 'FOO*.xml' -or -name 'BAR*.xml' -or -name 'BTT*.txt'"
;;
A2) ARGLINE="-name 'PO*xml' -or -name 'PR*xml'"
;;
...
esac
if [[ $# -gt 1 ]]; then
DAYS=$2
fi
find . -maxdepth 1 -type f -mtime +${DAYS} `${ARGLINE}`
The function fails when find doesn't find any files matching, with the following error:
No command '-name' found, did you mean: Command 'uname' from package 'coreutils' (main) -name: command not found
It however works correctly, when the number of days is such that find finds some files. It also fails when I try to pipe the output of succesful run into another command.
How should I correctly build the argument line for "find"?
-name
has to be in parentheses:args=( '(' -name ... -or -name ... etc. ')' )
– Kusalananda May 16 '18 at 08:45-mtime
to apply to all the-name
s, but-mtime +2 -name foo -or -name bar
is parsed as(-mtime +2 -name foo ) -or -name bar
. There's an implicit and between adjacent conditions, and and has higher priority than or. So you need to put the parenthesis there manually:-mtime +2 ( -name foo -or -name bar )
– ilkkachu May 16 '18 at 08:57-mtime
argument into the array, you will have to useargs=( -mtime +"$DAYS" '(' ... ')' )
where...
are the-name
tests. – Kusalananda May 16 '18 at 08:58-mtime
in the array... – Kusalananda May 16 '18 at 08:59