1

I'm trying to build up an array and then use it as the arguments to a script. When I echo out the command I think I'm building, it looks fine. But when I try to execute it, nothing happens. Here's a small example. In my actual script, I have to build the array at run time so I can't hard code (/tmp -iname "*.log*") And it has to run in older bash environments too, so I can't use += to append to an array.

#!/bin/bash

args=( /tmp )
args[${#args[@]}]=-iname
args[${#args[@]}]="\"*.log\""

# the following echoes what I expect: find /tmp -iname "*.log"
echo find "${args[@]}"

# this next line does not appear to find any files
find "${args[@]}"

echo the following finds files 
find /tmp -iname "*.log"

What am I doing wrong?

4
  • 1
    If you used set -x (or bash -x yourscript) and compared output between your script in that mode and running the command you want by hand, the issue would have been obvious. Commented May 26, 2015 at 19:47
  • 1
    (Short form: syntactic quotes are resolved early in the parsing process, before parameter expansion happens, so putting quotes inside of a piece of data, those quotes stay data when they're expanded and never become syntax). Commented May 26, 2015 at 19:48
  • 1
    ...instead of echo "${foo[@]}", by the way, you might consider getting in the habit of printf '%q ' "${foo[@]}"; echo. Commented May 26, 2015 at 19:49
  • 1
    echo "${foo[@]}" is pretty much useless, because echo doesn't show you the difference between echo "hello world" and echo "hello" "world", so it gives you no idea whatsoever as to whether or not you have quoting problems in your code. Commented May 26, 2015 at 19:50

1 Answer 1

3

Don't use quotes inside quotes, this should work:

#!/bin/bash

args=( /tmp )
args[${#args[@]}]=-iname
args[${#args[@]}]='*.log'

find "${args[@]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.