I want to exclude some files from my grep
command, for this I'm using parameter:
--exclude=excluded_file.ext
To make more easy to read I want to use a bash array with excluded files:
EXCLUDED_FILES=("excluded_file.ext")
Then pass ${EXCLUDED_FILES} array to grep
, like:
grep -Rni "my text" --exclude=${EXCLUDED_FILES}
How I can pass an array as parameter to grep
command?
Variables are not passed to programs as arguments; values are. Variables (especially arrays) are expanded by the shell into one or more words, and each word is passed as a separate argument to a program. In this specific case, the --exclude
option takes a single file name as its argument, so you need to build up multiple --exclude=foo
arguments from your array. One option:
for f in "${EXCLUDED_FILES[@]}"; do
opts+=( --exclude="$f" )
done
grep -Rni "my text" "${opts[@]}"
I guess you're looking for this:
grep -Rni "${excluded_files[@]/#/--exclude=}" "my text"
The parameter expansion "${excluded_files[@]/#/--exclude=}"
will expand to the expansion of the array excluded_files
with each field prefixed with --exclude=
. Look:
$ excluded_files=( '*.txt' '*.stuff' )
$ printf '%s\n' "${excluded_files[@]/#/--exclude=}"
--exclude=*.txt
--exclude=*.stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With