bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: variable assignment in string returning function


From: Chris F.A. Johnson
Subject: Re: variable assignment in string returning function
Date: Wed, 27 Jan 2010 11:54:55 -0500 (EST)
User-agent: Alpine 2.00 (LMD 1167 2008-08-23)

On Wed, 27 Jan 2010, Sharuzzaman Ahmat Raslan wrote:

> I found the behaviour of the function below is a little bit odd. Appreciate
> if someone can share his/her knowledge regarding the behaviour.
> 
> The output of the script will be:
> 
> sharuzzaman@debian:~$ ./case1.sh
> Nice behaviour,
> 
> Somehow, the backtick for foo() execute the function, echoing the correct
> output, but fails to set the variable $gang to the correct value. Because of
> that, the function bar() did not echoing anything because the variable $gang
> is null.
> 
> I would expect that $gang is set with the correct value and function bar()
> will work after that.
...
> #startscript----------
> #!/bin/bash
> 
> # test case for variable assignment in string returning function
> # case 1: function with echo
> 
> name="optimus"
> 
> foo () {
> if [ "$name" = "optimus" ]
> then
>         gang="good"
>         echo "Nice behaviour"
> else
>         gang="bad"
>         echo "Naughty behaviour"
> fi
> }
> 
> bar () {
> case "$gang" in
> 
>         good)
>                 echo "autobot"
>         ;;
> 
>         bad)
>                 echo "decepticon"
>         ;;
> esac
> }
> 
> behaviour=`foo`
> group=`bar`
> 
> echo $behaviour,$group
> #endscript------------------------

name="optimus"

foo () {
if [ "$name" = "optimus" ]
then
        gang="good"
        echo "Nice behaviour"
        return 0
else
        gang="bad"
        echo "Naughty behaviour"
        return 1
fi
}

bar () {
case "$gang" in

        good)
                echo "autobot"
                return 0
        ;;

        bad)
                echo "decepticon"
                return 1
        ;;
esac
}

behaviour=`foo` && gang=good || gang=bad
group=`bar` && gang=good || gang=bad

echo $behaviour,$group

-- 
   Chris F.A. Johnson                          <http://cfajohnson.com>
   ===================================================================
   Author:
   Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
   Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)




reply via email to

[Prev in Thread] Current Thread [Next in Thread]