shell脚本函数返回一个字符串

Lol*_*lly 5 unix linux shell

我是shell脚本的新手,我正在尝试创建一个简单的函数,它将返回作为参数传递的连接的两个字符串.我试过下面的代码

   function getConcatenatedString() {
       echo "String1 $1"
       echo "String2 $2"
       str=$1/$2
       echo "Concatenated String ${str}"
       echo "${str}"
   }
Run Code Online (Sandbox Code Playgroud)

//我正在调用上面的函数

  constr=$(getConcatenatedString "hello" "world")
  echo "printing result"
  echo "${constr}"
  echo "exit"
Run Code Online (Sandbox Code Playgroud)

使用上面的代码运行脚本时,我看到下面的输出,

   printing result
   String1 hello
   String2 world
   Concatenated String hello/world
   hello/world
   exit
Run Code Online (Sandbox Code Playgroud)

如果你看代码我首先调用函数然后我回显"打印结果"语句,但结果首先是"打印结果"并回显函数内部的语句.以下语句是否调用该函数

   constr=$(getConcatenatedString "hello" "world")
Run Code Online (Sandbox Code Playgroud)

要么

   echo ${constr}
Run Code Online (Sandbox Code Playgroud)

正在调用这个函数?

因为如果我注释掉#echo $ {constr}那么没有什么能得到回应!请澄清我.

pax*_*blo 10

第一个是调用函数并将所有输出(四个echo语句)存储到$constr.

然后,返回后,则呼应前导码printing result,$constr(由4行)和退出消息.

这就是有效的方法$(),它从封闭的命令中捕获整个标准输出.

听起来你想要echo在控制台上看到一些语句,而不是用它来捕获它们$().我认为您应该能够将它们发送到标准错误:

echo "String1 $1" >&2
Run Code Online (Sandbox Code Playgroud)