how to use regular expression in Bash Shell Scripting

Hi,

Actually i have written one test.sh (shell program) in bash.

Here i have a variables $a which stored the value package1.

Now I want to write a regular expression inside the if command that "if $a variable contains letter p in the begining of the value package1 then it is coming true. else it is coming false". For this i have written the following shell script.

a=package1
if grep "^p" $a
then
echo "true"
else
echo "false"
fi
echo "hello jim" | sed -e 's/hello/bye/'

But when i am running the following test.sh then i am getting the following error.

grep: can't open package1
false
bye jim

can anybody help me please to rectify this problem. Please help me. It is very urgent.

Grep expects a file name. In your case, package1 is not a file and hence the grep error.

You should rather do it as

echo $a | grep "^p"
if [[ $? -eq 0 ]] ; then
..
..
..
# a=package1
# case $a in p* ) echo "true" ;; * ) echo "no" ;;esac
true

thanks vino. Now it is working fine.But i want to know one thing that can you please explain the logic of this code, if you don't mind.

echo $2 | grep "^p"
if [[ $? -eq 0 ]] ; then

Thanks
Sunita

Hi Vino

Actually i wrote the following code, given by you.

Input is
a=package1
echo $2 | grep "^b"
echo $2
echo "$2"
if [[ $2 -eq 0 ]] ;
#if grep "^p" $a
then
echo "true"
else
echo "false"
fi

and the output of this is coming as

true
bye jim

here two spaces are coming in the $2 variable.

There was a typo in my earlier post. It should read $a instead of $2.
$? stands for the exit code of a command that was issued. For grep, the exit code is 0 if a successful pattern was matched. Else 1 will be returned.