简体   繁体   中英

Run command from variables in shell script

I wrote this piece of code to scan a directory for files newer than a reference file while excluding specific subdirectories.

#!/bin/bash

dateMarker="date.marker"
fileDate=$(date +%Y%m%d)
excludedDirs=('./foo/bar' './foo/baz' './bar/baz')
excludedDirsNum=${#excludedDirs[@]}

for (( i=0; i < $excludedDirsNum; i++)); do
    myExcludes=${myExcludes}" ! -wholename '"${excludedDirs[${i}]}"*'"
done

find ./*/ -type f -newer $dateMarker $myExcludes > ${fileDate}.changed.files

However the excludes are just being ignored. When I "echo $myExcludes" it looks just fine and furthermore the script behaves just as intended if I replace "$myExcludes" in the last line with the output of the echo command. I guess it's some kind of quoting/escaping error, but I haven't been able to eliminate it.

Seems to be a quoting problem, try using arrays:

#!/bin/bash

dateMarker=date.marker
fileDate=$(date +%Y%m%d)
excludedDirs=('./foo/bar' './foo/baz' './bar/baz')
args=(find ./*/ -type f -newer "$dateMarker")
for dir in "${excludedDirs[@]}"
do
    args+=('!' -wholename "$dir")
done
"${args[@]}" > "$fileDate.changed.files"

Maybe you also need -prune :

args=(find ./*/)
for dir in "${excludedDirs[@]}"
do
    args+=('(' -wholename "$dir" -prune ')' -o)
done
args+=('(' -type f -newer "$dateMarker" -print ')')

you need the myExcludes to evaluate to something like this:

\\( -name foo/bar -o -name foo/baz -o -name bar/baz \\)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM