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*)?

0

1 Answer 1

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 {} +
Sign up to request clarification or add additional context in comments.

4 Comments

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).
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).
...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).
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

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.