Reputation: 1795
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
Reputation: 1
if grep -q '>' <<<$line; then
..
else
..
fi
using grep is much better :)
Upvotes: 0
Reputation: 785058
Spaces are needed inside [[ and ]]
as follows:
if [[ "$line" == ">"* ]]; then
echo "found"
else
echo "not found"
fi
Upvotes: 7
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
Reputation: 1763
Spacing is important.
$ [[ ">test" == ">"* ]]; echo $?
0
$ [[ "test" == ">"* ]]; echo $?
1
Upvotes: 1