0

I have this code that returns the number of files in a directory with the name wordpress.*.tar.gz

This code works NUM_BACKUPS="$(ls -l ${POOL_PATH}/${BACKUP_PATH} | grep -c '\wordpress.*.tar.gz$')"

but I want to replace wordpress with a variable in my bash script

I've tried NUM_BACKUPS="$(ls -l ${POOL_PATH}/backup/${JAIL} | grep -c '\${JAIL}.*.tar.gz$')"

but it doesn't work

1 Answers1

0

${JAIL} is not getting expanded in the argument to grep because it's in single quotes. You could switch the single quotes to double quotes (and change \$ to just $), but that's kind of fragile. A more robust solution would be to do this entirely with globbing and bash arrays:

shopt -s nullglob
BACKUP_FILES=( "${POOL_PATH}/backup/${JAIL}/${JAIL}"*.tar.gz )
NUM_BACKUPS=${#BACKUP_FILES[@]}

You need nullglob to handle the case where the glob doesn't match any files. Without nullglob, you'd end up with NUM_BACKUPS set to 1 if you didn't have any files.

Note that the glob special characters (* in your case) have to be outside the double quotes in order to expand. But you want to keep double quotes around the variables in case they contain any whitespace.

satwell
  • 376