Bash Question

How to pass a regular expression to a function

I have a function that accepts more than one arguments. I am also passing a string with regular expression in it. But when it is getting

eval
uated others parameters are getting messed up.

Code is like below -

function foo() {
eval DIR_NAME='$'$1
MAX_DEPTH=$2
eval FILE_PATTERN=$3
RETENTION_PERIOD=$4
eval MOVE_PATH='$'$5
find . -maxdepth "$MAX_DEPTH" -type f -name "$FILE_PATTERN" -mtime +"$RETENTION_PERIOD" -print | ...
}

DIR_NAME="/my/path"
MAX_DEPTH=2
FILE_PATTERN="*.txt"
RETENTION_PERIOD=30
TARGET_DIRECTORY="/move/to/path"

foo DIR_NAME $MAX_DEPTH $FILE_PATTERN $RETENTION_PERIOD TARGET_DIRECTORY


Now the problem is at the
find
command
$FILE_PATTERN
is getting expanded and substituting itself with all the
.txt
file in the path and
RETENTION_PERIOD
,
MOVE_PATH
variables are getting substituted by other
.txt
files.

Any solution for this?

Answer
  1. There is no need to use eval here. Use indirect variable reference of BASH.
  2. *.txt is a glob pattern not regex and you should pass it quoted and use quotes inside in assignment to prevent shell expansion
  3. Don't use all uppercase variable names to avoid clash with shall's internal environment variables.
  4. Use local inside the function to define local variables to avoid overwriting global variables.

You can use:

foo() {
    local dir_name="${!1}"
    local max_depth="$2"
    local file_pattern="$3"
    local retention_period="$4"
    local move_path="${!5}"

    find . -maxdepth "$max_depth" -type f -name "$file_pattern" -mtime +"$retention_period" -print | ...
}

Then call it as:

dir_name="/my/path"
max_depth=2
file_pattern='*.txt'
retention_period=30
target_directory="/move/to/path"

foo dir_name "$max_depth" "$file_pattern" "$retention_period" target_directory