0

I have a variable whose value I want to pass into a command. However the $ is producing unusual results. It appears to be acting like an * and searching all directories. My code is:

"Please enter the test type: "
read test

result="pass"
search_result=`find ./logs/$test_2017_01_logs*/* -type f -name func_log -exec egrep $result {} \;`

echo "$search_result"

I only want to search the directory suffix that was read in by the user, not all directories which is what my code is doing.

Is the issue due to the concatenation of the passed in value ($test) and the remainder of the folder name (_2017_01_logs*)?

stevo
  • 171
  • 5
  • 16

1 Answers1

2

_ is a "word character" ([a-zA-Z0-9_]) and is understood as part of the variable you're addressing, which is thus the undefined $test_2017_01_logs.

To avoid this, you can enclose the variable name in curly brackets :

find ./logs/"${test}_2017_01_logs"*/* -type f -name func_log -exec egrep $result {} \;

Or, if we follow Charles Duffy's well-advised tips :

find ./logs/"$test"_2017_01_logs*/* -type f -name func_log -exec egrep -h -e "$result" /dev/null {} +
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • 1
    Might also want to add quotes around `$result`, such that it doesn't get word-split (with words beyond the first interpreted as additional filenames). – Charles Duffy Feb 01 '17 at 15:14
  • 2
    I'd also suggest `-exec egrep -h -e "$result" /dev/null {} +` -- that way we don't run `grep` more times than we need to, and (due to the preceding `-e`) interpret `result` as a literal string even if it starts with a dash. (The `-h` suppresses filenames in output, to get equivalent behavior to the current use even when multiple names are passed; if you want them, take it out). – Charles Duffy Feb 01 '17 at 15:17
  • 2
    ...the `/dev/null` is there because `grep` changes its behavior in some cases based on how many filenames are passed; having it present ensures that you get consistent behavior no matter how many results `find` is adding to the command line, and means that if the idiom is reused with `xargs`, we don't get an instance reading from stdin with an implementation that follows through with invoking in the 0-results-found case (IIRC, the MacOS implementation is one of these). – Charles Duffy Feb 01 '17 at 15:18
  • 2
    Oh. And if `$test` contains spaces or glob characters that should be treated as literal (including square brackets), you'll want that quoted too. `./logs/"$test"_2017_01_logs*/*` will do, or `"./logs/${test}_2017_01_logs"*/*` -- the only thing to be sure of is that we're *not* quoting the `*`s – Charles Duffy Feb 01 '17 at 15:20