0

Here's an example :

VALID_MODELINE_FMT=$'\'"[0-9]+x[0-9]+@[0-9]+" ([0-9]+)(\.[0-9]+)?( [0-9]+){8} [+|-]hsync [+|-]vsync\''
REJECTED_MODELINES=$(printf "$MODELINES_STR" | grep -vE $VALID_MODELINE_FMT)

When running the command, I get errors that do not make any sense:

grep: ([0-9]+)(\.[0-9]+)?(: No such file or directory
grep: [0-9]+){8}: No such file or directory
grep: [+|-]hsync: No such file or directory
grep: [+|-]vsync": No such file or directory

When substituting the variable everything works:

REJECTED_MODELINES=$(printf "$MODELINES_STR" | grep -vE '"[0-9]+x[0-9]+@[0-9]+" ([0-9]+)(\.[0-9]+)?( [0-9]+){8} [+|-]hsync [+|-]vsync'

Basically, all I want to do is simply centralize the regex format string inside one variable because it's used at a few places. Seems I just can't, probably because of poor substitution design inherent to shell programming. However, I wonder if I can circumvent this, ideally without meddling with single quotes.

Thanks! :)

3
  • 2
    You need to quote format variable in grep command. However do check your VALID_MODELINE_FMT by echoing it to make sure if that is what you want. Commented Aug 31, 2021 at 5:33
  • I suggest you also post your sample input with expected output. Commented Aug 31, 2021 at 5:35
  • @Yannick: In zsh, your approach would work, but not in bash. Without quotes, bash does wildcard expansion on what you want to be your grep regexp. However, I don't see the reason for the initial $'\' of the regexp. The first regexp character is ", which does not have a particular meaning inside the regexp. There is no need for escaping it. Commented Aug 31, 2021 at 5:42

1 Answer 1

1

You have to quote the variable expansion. Also, do not printf "$var" - use "%s".

printf "%s" "$MODELINES_STR" | grep -vE "$VALID_MODELINE_FMT"

Check your scripts with https://shellcheck.net - it will get such mistakes. Prefer to use lower case variables, uppper case variables like COLUMN PATH PWD USER and many more are conceptually for exported variables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.