LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   String Manipulations in Shell Script (https://www.linuxquestions.org/questions/programming-9/string-manipulations-in-shell-script-547066/)

ramakula@gmail.com 04-18-2007 10:53 AM

String Manipulations in Shell Script
 
Hi All,

I need to check the one variable contains the given string or not.

Ex:-

#!/bin/sh
host="$1"
service="$2"
t="this is shell script"

if [condition to check variable $t contains "shell" string] ; then
echo "Yes"
else
echo "No"
fi

how to write condition to check $t contains that string?

and here i don't want to use files. i only need to get with string manipulation.

Please help!

matthewg42 04-18-2007 11:12 AM

Please use [code] tags in your post to mark up program code for improved readability.

You can use the case statement to easily check for patterns:
Code:

case "$t" in
*shell*)
    echo "contains shell"
    ;;
*)
    echo "doesn't contain "shell'"
    ;;
esac


ghostdog74 04-18-2007 11:36 AM

a few other ways
Code:

t="this is shell script"
if [ ! -z "$(echo $t | awk '/shell/')" ];then echo "found string"; fi

Code:

t="this is shell script"
awk -v var="$t" 'BEGIN  { if ( var ~ /shell/) print "found string" }'


matthewg42 04-18-2007 11:49 AM

You could also use grep, like this:
Code:

if echo "$t" |grep -q shell; then
        echo yes
else
        echo no
fi

...however, as with using awk, this requires the spawning of an external program, which is slower than using the internal case statement. Doesn't matter much if you're just testing once, but if you're doing it in a tight loop, it can make a lot of difference.

It's a good idea to get into the habit of using shell internals whenever possible.

makyo 04-18-2007 01:48 PM

Hi.

The bash shell has special provisions for pattern matching when used with [[ string == pattern ]] symbols and syntax. For example:
Code:

#!/bin/sh

# @(#) s1      Demonstrate bash pattern matching.

t="this is shell script"

if [[ "$t" == shell ]]  # WRONG -- see later post
then
        echo " Keyword shell appeared"
else
        echo " the string shell did not appear"
fi

Which produces:
Code:

% ./s1
 Keyword shell appeared

Described around line 300 and 1350 in man bash (described, but not illustrated with examples -- this comment being a gentle notice to help identify deficiencies in Linux man pages). I also looked, but did not find, a reference to this feature in the usually helpful abs at http://www.tldp.org/LDP/abs/html/index.html ... cheers, makyo

( edit 1: typo )
( edit 2: warning for incorrect code )

ghostdog74 04-18-2007 06:28 PM

Quote:

Originally Posted by makyo
...
Which produces:
Code:

% ./s1
 Keyword shell appeared


however, mine produced
Code:

# ./test.sh
 the string shell did not appear

the correct format should be using =~, not ==
Code:

# ./test.sh
 Keyword shell appeared


makyo 04-18-2007 07:20 PM

Hi, ghostdog74.

I think you may be using the wrong shell.
Quote:

When the == and != operators are used, the string to the right
of the operator is considered a pattern and matched according to
the rules described below under Pattern Matching. The return
value is 0 if the string matches or does not match the pattern,
respectively, and 1 otherwise. Any part of the pattern may be
quoted to force it to be matched as a str

-- excerpt from man bash
Whereas:
Quote:

The operators `=~' and `!~' are like `!=' and `==' except that
the right hand side is a glob-pattern (see Filename substitution)
against which the left hand operand is matched. This reduces the need
for use of the switch builtin command in shell scripts when all that is
really needed is pattern matching.

-- excerpt from man tcsh
If the operator =~ is used with bash, it produces:
Code:

./s4: line 8: conditional binary operator expected
./s4: line 8: syntax error near `=~'
./s4: line 8: `if [[ "$t" =~ shell ]]'

cheers, makyo

( edit 1: grammar )

ghostdog74 04-18-2007 08:45 PM

hi makyo,
i am using GNU bash.
from my bash man page
Quote:

...
[[ expression ]]
.....

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expres‐sion and matched accordingly (as in regex(3)).
....
as with many other programming languages, the "==" checks for equality. So if "t" is "this is a shell script", it will not equal "shell". I think this would be the correct behaviour. If i change "t" variable to "shell", and use "==", then i get the correct output.

makyo 04-18-2007 09:58 PM

Hi, ghostdog74.

Thanks for posting that. Yes, I see that text in man bash3, but not in man bash2.

There have been some incompatibilities between version 2 (I use 2.05b.0(1)) and version 3. In a way, this one of those situations, and in a way it is not because they both can be made to match without using the =~ operator.

I have versions for bash2 and bash3. I added extra regular expression elements and they both match successfully. My earlier post without the asterisks was incorrect (I most likely ran the wrong script, or posted the output from an earlier run). You are correct for the case where the string shell alone is used. I recall being surprised that it worked without the asterisks.

Here is bash2:
Code:

#!/bin/bash

# @(#) s2      Demonstrate bash pattern matching.

echo " This is bash version $BASH_VERSION"

t="this is shell script"

if [[ "$t" == *shell* ]]
then
        echo " Keyword shell appeared"
else
        echo " the string shell did not appear"
fi

Which produces:
Code:

% ./s2
 This is bash version 2.05b.0(1)-release
 Keyword shell appeared

And here is bash3:
Code:

#!/bin/bash3

# @(#) s5      Demonstrate bash pattern matching.

echo " This is bash version $BASH_VERSION"

t="this is shell script"

if [[ "$t" == *shell* ]]
then
        echo " Keyword shell appeared"
else
        echo " the string shell did not appear"
fi

this produces:
Code:

% ./s5
 This is bash version 3.00.16(1)-release
 Keyword shell appeared

I like the =~ operator better because it is used by perl, as in:
Code:

$t =~ /shell/
but not everyone is using bash3, so I personally will probably not use it in bash shell scripts just yet ... cheers, makyo

( edit 1: clarify )

ramakula@gmail.com 04-19-2007 03:53 AM

String Manipulations in Shell Script from nagios
 
Thank you all for replay,

your replied code nippet are working fine.

But when I am calling from "Nagios Monitoring" Tool that code nippets are not working!
Nagios is a Monitoring Tool which monitors the hosts,services of the system. http://nagios.org/

I need to check service statuses of the linux.
This is the code.. what i am doing.
---------------------------------------------------------
Code:

#!/bin/sh
host="$1"
service="$2"
t=`/etc/init.d/$service status`
if echo "$t" |grep -q running; then
        echo "OK - $service service is running."
        exit 0
else
        echo "Critical - $service service is stopped."
        exit 2
fi

-----------------------------------------------------------
when I am excuting this code is working fine from command prompt.

But when Nagios executing this shell script it not working, Because no string is storing in to $t variable. Nagios not able to execute `/etc/init.d/$service status` command in above code.

So how do I execute this from Nagios for checking service status?

Is there any way to check service statuses of linux from nagios?
Is there any Nagios plugin for to check service statuses?

Please help!

makyo 04-19-2007 05:26 AM

Hi.

The code is difficult to read, that is why the responders use CODE blocks to display the scripts and fragments.

The nagios aspect seems better related to the new thread at http://www.linuxquestions.org/questi...15#post2717015 ... cheers, makyo

ghostdog74 04-19-2007 08:04 AM

Quote:

Originally Posted by ramakula@gmail.com
...

But when Nagios executing this shell script it not working, Because no string is storing in to $t variable. Nagios not able to execute `/etc/init.d/$service status` command in above code.
....

can you show the value of t, like
Code:

#!/bin/sh
host="$1"
service="$2"
echo $host
echo $service
t=`/etc/init.d/$service status`
echo $t
exit
#if echo "$t" |grep -q running; then
 #        echo "OK - $service service is running."
  #      exit 0
#else
 #        echo "Critical - $service service is stopped."
  #      exit 2
#fi


ramakula@gmail.com 04-19-2007 08:23 AM

not displaying any thing $t value
 
Quote:

Originally Posted by ghostdog74
can you show the value of t, like
Code:

#!/bin/sh
host="$1"
service="$2"
echo $host
echo $service
t=`/etc/init.d/$service status`
echo $t
exit
#if echo "$t" |grep -q running; then
 #        echo "OK - $service service is running."
  #      exit 0
#else
 #        echo "Critical - $service service is stopped."
  #      exit 2
#fi


Quote:

Originally Posted by ghostdog74
can you show the value of t, like
Code:

#!/bin/sh
host="$1"
service="$2"
echo $host
echo $service
t=`/etc/init.d/$service status`
echo $t
exit
#if echo "$t" |grep -q running; then
 #        echo "OK - $service service is running."
  #      exit 0
#else
 #        echo "Critical - $service service is stopped."
  #      exit 2
#fi

->no output if this script calling from nagios.


when I am running this script from terminal as root user it will displaying:
acpid (pid 6857) is running...

ghostdog74 04-19-2007 09:24 AM

how does nagios call the script? and does the root use nagios to call the script? or is there a nagios user that will call the script? if the nagio's user is going to call the script, make sure it has permission to execute.

ramakula@gmail.com 04-19-2007 10:23 AM

how to give permissions to nagios user
 
Quote:

Originally Posted by ghostdog74
how does nagios call the script? and does the root use nagios to call the script? or is there a nagios user that will call the script? if the nagio's user is going to call the script, make sure it has permission to execute.

yes, script is executing nagios user.

script is executing from nagios, But only command `/etc/init.d/$service status` is not executing and no output is storing in variable $t.

Please let me know how to give permission to access.

Thank you.


All times are GMT -5. The time now is 06:12 AM.