0

I need to check if a word is starting with ">" character or not

for example A=">abcd" should return true, B="assdf" should not.

I Tried the following snippets but it does not work

if [ "$A" == "\>*" ]; then
    echo "True"
fi

The following does not work also

A=">dfssdfsd"
    if [[ "$A" =~ "\>*" ]]; then
    echo "aaa"
fi

Thank you

  • Use double brackets and =~ i.e `if [[ "$A" =~ ^\> ]]` – 123 Mar 15 '16 at 13:59
  • This does work. Thank you – Ionut Cosmin Mihai Mar 15 '16 at 14:03
  • Why is this duplicate, > is a special character, I already looked over that answer it does not answer to my question. – Ionut Cosmin Mihai Mar 15 '16 at 14:10
  • All of the answers in the duplicate work for your problem, therefore it is a duplicate. A single character difference is not a new question. If your question is how to escape special characters then ask that. – 123 Mar 15 '16 at 14:19
  • As 123 mentioned not to double-quote the RegEx, you also do not need to use double-quotes on `$A` when using double square brackets, e.g., `A="> dfssdfsd"; [[ $A =~ ^\>* ]] && echo "Yes"` will answer `Yes` as the space in `"> dfssdfsd"` will not split inside of double square brackets. Note that I know `$A` in the example is `>dfssdfsd` without a space and my example is to show that there is no splitting when inside double square brackets and therefore why `$A` does not need to be quoted either. – user3439894 Mar 15 '16 at 15:12

1 Answers1

0

You can use the following :

expr "$A" : '>'
$ if [ 0 -ne $(expr 'test' : '>') ]; then echo "True"; else echo "False"; fi
False
$ if [ 0 -ne $(expr '>test' : '>') ]; then echo "True"; else echo "False"; fi
True
Aaron
  • 24,009
  • 2
  • 33
  • 57