1

I'm having some troubles getting a shell script to work. I'm trying to dynamically generate the find command based on user input and I'm running into the problem that my variables in the find command are getting enclosed in single quotes like already described here.

So if i echo my variable they'll show up like -iname "*.flv" but once they are in the find command they are -iname "*.flv" with single quotes and the find command isn't executed.

I've tried to implement the answers given in that other SO thread but I can't figure it out.

Any idea what's wrong there?

Thanks!

if [[ ! "$medium" == "" ]]
  then
    needles=$needles' -iname "'*$medium*'"'
  fi

  echo $needles
  #-iname "*.flv"

  echo $path
  #/Users/user/Movies/

  find "$path" $needles -type f -exec basename {} \; | gshuf -n 1
  # + find '/Users/user/Movies' -iname '"*dvd*"' -type f -exec basename '{}' ';'

1 Answer 1

3

As I said in my answer to the linked question, you don't have mysteriously appearing single quotes. The single quotes are part of bash's trace display of your command line. What you have are extraneous double quotes, and you have put them there yourself. So don't do that.

Your best bet is to make needles an array; there is an example in the answer to the linked question, too, but here's the solution for your particular problem:

# Make needles an empty array
needles=()

# If medium is not empty, add two parameters to needles:
if [[ -n $medium ]]; then
  # We quote *$medium* so that the asterisks won't get glob-expanded, and 
  # so that the value won't get word split even if it includes whitespace.
  # NO QUOTES ARE ADDED TO THE VALUE.
  needles+=(-iname "*$medium*")
fi

# The expression "{needles[@]}" means:
#   expand this into each element of needles (needles[@])
#   and don't expand the elements even if they include whitespace ("")
find "$path" "${needles[@]}" -type f -exec basename {} \; | gshuf -n 1
1
  • Thank you, it's working now! I was actually trying to implement the array solution you suggested in that other thread but wasn't able to get it working.
    – mediocre
    Feb 17, 2014 at 0:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .