1

I'm new to BASH scripting. I am trying to use variables in commands. What I want is, for example, If the directory "resDir" had the files "patternOne.txt", "patternTwo.txt", "mylist.txt", I'd want the array "arr" to have both "patternOne.txt" and "patternTwo.txt" in it. I am currently doing that this way:

resDir = /home/username/repo/results
str = "pattern"
arr = ($(ls resDir| grep str))

Is this correct or are there any glaring mistakes? Could someone explain when variables need quotations and when they don't?

4
  • 1
    If it works, it is correct. If it doesn't, you should describe how it's behavior is not what you want. Commented Jul 2, 2015 at 20:20
  • @ScottHunter, ...well, the first part can be misleading, particularly in bash -- lots of things appear to work but have hidden gotchas or corner cases. But here, the details of how code doesn't work shouldn't be so card to figure out. Commented Jul 2, 2015 at 20:21
  • Suggested reading: mywiki.wooledge.org/ParsingLs, and the entirety of mywiki.wooledge.org/BashPitfalls (which showcases at least two of three major errors in this code). Commented Jul 2, 2015 at 20:22
  • ...also, the StackOverflow help center -- as it is, this isn't well-formed enough to be a good question. stackoverflow.com/help/mcve is one particular place worthy of focus. Commented Jul 2, 2015 at 20:29

1 Answer 1

1
resDir=/home/username/repo/results
str="pattern"
arr=( "$resDir"/*"$str"* )
  1. Whitespace MUST NOT be placed around the = on assignments; doing so makes the syntax no longer an assignment. (resDir = /home/username/repo/results runs a command named resDir, passing it = as its first argument).
  2. Expansions are almost always safe to quote. Exceptions (such as the right-hand side of [[ ]] operators = and =~, when the expanded string should be treated as a glob pattern or regex rather than as literal text) are very rare. By contrast, bugs caused by failing to quote expansion are exceedingly commonplace.
  3. *s MUST NOT be quoted, if you want them to trigger glob expansion rather than be treated literally.
  4. ls MUST NOT be used in scripting.

By the way -- the resulting structure is an array. Below is an example of the syntax for expanding array contents:

printf '%q\n' "${arr[@]}"
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.