2

Long story short, narrowed my problem down to a one-liner:

for a in {a..z}; do echo "-$a" | grep "\-$a"; done

This prints all letters but -e and -n.

Looks like Linux version, bash version, flags to grep (-P, -E) etc do not matter!
Tested environments:

  1. GNU bash, version 3.2.57(2)-release (x86_64-suse-linux-gnu) on SUSE Linux Enterprise Server 11 SP4
  2. GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin) on Cygwin (base-cygwin 3.8-1; cygwin32 2.10.0-1)
  3. rextester (bash online compiler; GNU bash 4.3.46)

Why are not -e and -n printed?
(Removing the dashes in the code also removes the problem)

0

1 Answer 1

7

Problem is that -e, -n are valid echo options and echo is not printing them.

Moreover you should use -- in grep to separate options and pattern. Suggest you to use -F option in grep as well for fixed string search.

You may use:

for a in {a..z}; do grep -F -- "-$a" <<< "-$a"; done

-a
-b
-c
-d
-e
-f
-g
-h
-i
-j
-k
-l
-m
-n
-o
-p
-q
-r
-s
-t
-u
-v
-w
-x
-y
-z

Note that you may also use printf instead of echo:

for a in {a..z}; do printf -- '-%s\n' "$a" | grep -F -- "-$a"; done
Sign up to request clarification or add additional context in comments.

1 Comment

plus 1 for suggesting printf over echo.

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.