0

Goal: get all mp4 names in a directory and store them in a variable. I want to get the output of find command with some variables(arguments passed in)

dir='.'
search="-iname '*.mp4'"

find . -iname '*.mp4'             # works but need to use variable instead of hard code

find $dir $search                 # failed
output=$(find $. "$search")       # failed
...                               # all failed

Huakun Shen
  • 312
  • 2
  • 9
  • Why do you need `-iname` as part of your `search` variable? Why not `search="*.mp4"` then `find $dir -iname $search`, and `output=$(find $dir -iname $search)`? The problem is that `"-iname '*.mp4"` will be treated as a single string argument to `find` if you use `search="-iname '*.mp4'`. – lurker Jun 04 '20 at 01:51
  • I tried this just now, but it didn't work for me, either. – Huakun Shen Jun 04 '20 at 02:02
  • We'll you need to show exactly what you did. I tried it and it worked fine for me. – lurker Jun 04 '20 at 02:27
  • You are most likely seeing different results based on whether or not you have any `.mp4` files in the current directory. If you do, it'll fail with an error or find too few matches. If you don't, it'll work as expected. – that other guy Jun 04 '20 at 02:49

1 Answers1

0

EDIT: The first method doesn't work in all cases, use the second one.

The single quotes around your '*mp4' mean you're searching for a file name with single quotes around it. Remove them and it works:

dir="."
search="-iname *.mp4"
find "$dir" $search

Another way to do it, which would allow spaces in your search strings and prevent other pitfalls from not using quoted variables, is to use arrays for your additional arguments:

dir="."
args=("-iname" "*.mp4")
find "$dir" "${args[@]}"
MHebes
  • 2,290
  • 1
  • 16
  • 29
  • Thank you! the first method didn't work for me, but the second one works. – Huakun Shen Jun 04 '20 at 02:36
  • 1
    The first method fails if you have `mp4` files in the current directory, or if either the nullglob or failglob options are set. The second way always works, and it's therefore preferable – that other guy Jun 04 '20 at 02:51