I'm creating PowerShell and Bash scripts to standardise our usage of the former's Get-ChildItem
and Select-String
and the latter's grep
.
As part of the Bash script, I'm taking command-line arguments, parsing the comma-delimited values for the filename includes (plural), and trying to pass them to Grep's --include=
but encountering all sorts of difficulties.
Initially, I was trying to use brace expansion, but I abandoned this because (1) I couldn't get it to work and (2) I read that this technically isn't supported by grep and the proper solution is to use multiple includes anyway.
Now, I'm trying to use those multiple includes which I have managed to get working, but only if the value doesn't contain a space - if it does then the script does nothing, presumably because the values aren't quoted, but I haven't been able to get a quoted version working, even though copying and pasting the output of $grepstring
in the shell works fine.
Here's a simplified version of the script:
#!/bin/bash
include="$1"
if [[ $include == "," ]]; then
IFS=',' read -r -a includearray <<< "$include"
includemulti=""
firstloop="yes"
for element in "${includearray[@]}"
do
# Trim leading and trailing whitespace
element="${element## }"
element="${element%% }"
if [[ "$firstloop" == "yes" ]]; then
firstloop="no"
includemulti+="--include=$element"
# includemulti+="--include=\"$element\""
# includemulti+="--include='"$element"'"
# includemulti+='--include="'$element'"'
# includemulti+='--include="'"$element"'"'
# includemulti+="--include='$element'"
else
includemulti+=" --include=$element"
# includemulti+=" --include=\"$element\""
# includemulti+=" --include='"$element"'"
# includemulti+=' --include="'$element'"'
# includemulti+=' --include="'"$element"'"'
# includemulti+=" --include='$element'"
fi
done
grep -ERins $includemulti "<pattern>" "<path>"
grepstring="grep -ERins $includemulti \"<pattern>\" \"<path>\""
echo $grepstring
else
grep -ERins --include="$include" "<pattern>" "<path>"
fi
Does work:
bash ~/test.sh 'Hello*.txt, *.sh'
bash ~/test.sh 'Hello W*.txt'
Does not work:
bash ~/test.sh 'Hello W*.txt, *.sh'
I'm starting to wonder if it's just easier to call grep
multiple times with one include for each one...
grep
. A suitable shell will expand a brace pattern and supply the result as a set of arguments to whatever command is present. – Chris Davies Jul 03 '23 at 17:10includemulti
variable splits, hence the issue. – annahri Jul 03 '23 at 20:55--include={foo,bar}
into--include=foo --include=bar
. just that combining that with any sort of a variable is difficult to impossible in Bash (but maybe easier in other shells, though possibly still fishy) – ilkkachu Jul 05 '23 at 12:15