Stephopolis
Stephopolis

Reputation: 1795

Bash: If line begins with >

I want an if/then statement in Bash and I can't seem to get it to work. I would like to say "If the line begins with > character, then do this, else do something else".

I have:

while IFS= read -r line
do
    if [[$line == ">"*]]
    then
        echo $line'first'
    else
        echo $line'second'
    fi
done

But it isn't working. I also tried to escape the ">" by saying:

if [[$line == ^\>*]]

Which didn't work either. Both ways I am getting this error:

line 27: [[>blah: command not found

Suggestions?

Upvotes: 3

Views: 8799

Answers (4)

Somya Arora
Somya Arora

Reputation: 1

if grep -q '>' <<<$line; then
   ..
else
   ..
fi

using grep is much better :)

Upvotes: 0

anubhava
anubhava

Reputation: 785058

Spaces are needed inside [[ and ]] as follows:

if [[ "$line" == ">"* ]]; then 
    echo "found"
else
    echo "not found"
fi

Upvotes: 7

hek2mgl
hek2mgl

Reputation: 157947

This attempt attempt uses a regex:

line="> line"
if [[ $line =~ ^\> ]] ; then 
    echo "found"
else
    echo "not found"
fi

This one uses a glob pattern:

line="> line"
if [[ $line == \>* ]] ; then 
    echo "found"
else
    echo "not found"
fi

Upvotes: 2

SylvainD
SylvainD

Reputation: 1763

Spacing is important.

$ [[ ">test" == ">"* ]]; echo $?
0
$ [[ "test" == ">"* ]]; echo $?
1

Upvotes: 1

Related Questions