Click to See Complete Forum and Search --> : simple bash question


hfawzy
12-07-2002, 08:01 AM
Hi there,
I'm learning bash and I have a simple question.

When, for example I search for a given pattern in a file (using grep), how do I check whether the grep command has returned any results?
Thank you

hfawzy

bwkaz
12-07-2002, 09:22 AM
$? contains the exit status of any command. If grep matches anything, its exit status will be zero, and if not, it will be something else.

So you can do one of two things. Test the exit status immediately (like if grep "my regex string" /path/to/files ; then), or test it later, explicitly, like this:

#!/bin/bash

grep "my string" /path/to/files/*

if [ $? -eq 0 ] ; then
# string found somewhere
else
# string not found, or error encountered
fi

hfawzy
12-07-2002, 09:51 AM
thanks for your help:)

hfawzy
12-07-2002, 12:43 PM
hi,
I have another question :
Is is possible to check whether the user who is executing the program is root, using the whoami command?
P.S: I know that there is an enviroment variable called $USER but I want to use "whoami"

Thank you
hfawzy

bwkaz
12-07-2002, 08:16 PM
Running man whoami returns with the fact that first, it is entirely equivalent to running id -un, and that second, there is more documentation available as a TexInfo manual (accessed with info whoami).

Running man id gives me a bunch of options on what to print, and also another note that more info is available in info id.

BUT, that doesn't tell you how to compare it to anything. What I'd do is something like:

#!/bin/bash

if [ "$(whoami)" != "root" ] ; then
echo "You are not root! You can't do this!"
exit 1
fi

# ... rest of script The $(...) makes the shell execute whatever's inside it (whoami), and substitute the stdout of that command in for the $(...) construct. So it will put the current user name inside the quotes on the left. The rest is just like how you'd do the check with $USER.

hfawzy
12-08-2002, 10:05 AM
thanks again :D

bwkaz
12-08-2002, 10:20 AM
No problem, happy to help. :)

alAx
12-08-2002, 10:46 AM
grep "my string" /path/to/files/*
if [ $? -eq 0 ] ; then
# string found somewhere
else
# string not found, or error encountered
fi


What scripting language is that?

I get so confused with so many

thanks in advance

alAx

hfawzy
12-08-2002, 01:11 PM
It's the BASH ( Bourne Again SHell) programming language.For more information, check out its manual ( man bash )
hfawzy

bwkaz
12-08-2002, 07:16 PM
Originally posted by hfawzy
It's bash And that's why the script starts with #!/bin/bash, to tell the system to run it using the interpreter named /bin/bash, which is the bash shell.

alAx
12-09-2002, 11:50 AM
Thanks for the reply. suppose it makes sense. I just didnt know the bash shell had its own scripting language.

alAx