Search code examples
bashparameter-passingconcatenationbackticks

bash passing value into command


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


Solution

  • _ 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 {} +