Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script function return a string

Tags:

linux

shell

unix

I am new to shell scripts, I am trying to create a simple function which will return the concatenated two strings that are passed as parameters. I tried with below code

   function getConcatenatedString() {
       echo "String1 $1"
       echo "String2 $2"
       str=$1/$2
       echo "Concatenated String ${str}"
       echo "${str}"
   }

//I am calling the above function

  constr=$(getConcatenatedString "hello" "world")
  echo "printing result"
  echo "${constr}"
  echo "exit"

I see the below output when running the script with above code,

   printing result
   String1 hello
   String2 world
   Concatenated String hello/world
   hello/world
   exit

If you look at the code I am first calling the function and then I am echoing "printing result" statement, but the result is first comes the "printing result" and echos the statement inside the function. Is the below statement calling the function

   constr=$(getConcatenatedString "hello" "world")

or

   echo ${constr}

is calling the function ?

Because if I comment out #echo ${constr} then nothing is getting echoed !!! Please clarify me.

like image 766
Lolly Avatar asked Aug 01 '12 11:08

Lolly


1 Answers

The first is calling the function and storing all of the output (four echo statements) into $constr.

Then, after return, you echo the preamble printing result, $constr (consisting of four lines) and the exit message.

That's how $() works, it captures the entire standard output from the enclosed command.

It sounds like you want to see some of the echo statements on the console rather than capturing them with the $(). I think you should just be able to send them to standard error for that:

echo "String1 $1" >&2
like image 179
paxdiablo Avatar answered Oct 10 '22 18:10

paxdiablo