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: Mart Frauenlob
Subject: Re: variable assignment in string returning function
Date: Wed, 27 Jan 2010 14:10:49 +0100
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20100111 Thunderbird/3.0.1

On 27.01.2010 13:49, Sharuzzaman Ahmat Raslan wrote:
> Hi,
> 
> 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.
> 
> Thanks.
> 
> 
> System information:
> 
> OS: Debian Squeeze
> Hardware: Intel x86 Pentium 4
> Bash: 4.1.0(1)-release (i486-pc-linux-gnu)
> 
> 
> 
> #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------------------------
> 

the 'gang' variable is set in a subshell. it is destroyed as the
subshell exits. that's why it's not available at the time the bar()
function is run.


reply via email to

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