Grep with a Variable in a Script

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

1 Answer

${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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest